package com.xoa.service.WFE.WFERunner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xoa.dao.WFE.WFEFlowProcessMapper;
import com.xoa.dao.WFE.WFEFlowRunPrcsMapper;
import com.xoa.dao.WFE.WFEFlowTypeModelMapper;
import com.xoa.dao.WFE.WFEFormTypeMapper;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.document.DocumentMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.flowRunFeedback.FlowRunFeedbackMapper;
import com.xoa.dao.flowhook.FlowHookMapper;
import com.xoa.dao.flowplugin.FlowPluginMapper;
import com.xoa.dao.notify.NotifyMapper;
import com.xoa.dao.sms.SmsBodyMapper;
import com.xoa.dao.sms.SmsMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.*;
import com.xoa.dev.workFlow.controller.WorkFlowCreateController;
import com.xoa.global.proxy.TriggerUtils.Trigger;
import com.xoa.model.common.SysPara;
import com.xoa.model.department.Department;
import com.xoa.model.document.DocumentModel;
import com.xoa.model.document.DocumentModelWithBLOBs;
import com.xoa.model.document.SysRuleModel;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.flowRunFeedback.FlowRunFeedback;
import com.xoa.model.flowplugin.FlowPluginModel;
import com.xoa.model.notify.Notify;
import com.xoa.model.sms.Sms;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.plugin.workflow.WorkFlowPlugin;
import com.xoa.service.WFE.WFE;
import com.xoa.service.WFE.WFEFactory.WFEFlowProcess;
import com.xoa.service.WFE.WFEFactory.WFEFlowType;
import com.xoa.service.WFE.WFEFactory.WFEFormType;
import com.xoa.service.WFE.WFELog.WFELog;
import com.xoa.service.document.DocumentSerivce;
import com.xoa.service.sys.SystemInfoService;
import com.xoa.service.work.WorkService;
import com.xoa.service.work.impl.WorkServiceImpl;
import com.xoa.util.*;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.constants.DocumentConstants;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//工作信息
@Service
public class WFEFlowRunInfo extends WFE {
    @Autowired
    private WorkFlowPlugin workFlowPlugin;

    @Autowired
    protected WFEFlowProcessMapper wfeFlowProcessMapper;
    @Autowired
    private FlowFormTypeMapper flowFormTypeMapper;

    @Autowired
    private FlowRunMapper flowRunMapper;

    @Autowired
    private FlowRuleMapper flowRuleMapper;

    @Autowired
    protected WFEFlowType wfeFlowType;

    @Autowired
    protected WFEFormType wfeFormType;

    @Autowired
    protected WFEFlowProcess wfeFlowProcess;

    @Autowired
    protected WFEFlowRun wfeFlowRun;

    @Autowired
    protected WFEFlowRunPrcs wfeFlowRunPrcs;

    @Autowired
    protected WFEFlowTypeModelMapper wfeFlowTypeModelMapper;

    @Autowired
    protected WFEFormTypeMapper wfeFormTypeMapper;

    @Autowired
    protected WorkMapper workMapper;

    @Autowired
    protected FlowProcessMapper flowProcessMapper;

    @Autowired
    private FlowTypeModelMapper flowTypeModelMapper;

    @Autowired
    protected FlowTiggerMapper flowTiggerMapper;

    @Autowired
    protected FlowPluginMapper flowPluginMapper;

    @Autowired
    protected FlowHookMapper flowHookMapper;

    @Autowired
    protected FlowRunFeedbackMapper flowRunFeedbackMapper;

    @Autowired
    protected WorkService workService;


    @Autowired
    protected FlowSortMapper flowSortMapper;

    @Autowired
    protected SmsMapper smsMapper;

    @Autowired
    protected SmsBodyMapper smsBodyMapper;

    @Resource
    WFEFlowRunPrcsMapper WFEFlowRunPrcsMapper;
    @Autowired

    protected FlowRunAttachMapper flowRunAttachMapper;

    @Autowired
    private WFELog wfeLog;

    @Autowired
    private FlowRunLogMapper flowRunLogMapper;

    @Autowired
    private FlowRunPrcsMapper flowRunPrcsMapper;
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private SystemInfoService systemInfoService;

    @Autowired
    private WorkServiceImpl workServiceImpl;

    @Autowired
    private ToBeReadMapper toBeReadMapper;

    @Autowired
    private DocumentSerivce documentSerivce;

    @Autowired
    private SysParaMapper sysParaMapper;

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    private RelationFuncMapper relationFuncMapper;

    @Autowired
    private FlowOperationMapper flowOperationMapper;

    @Autowired
    WorkFlowCreateController workFlowCreateController;

    @Autowired
    private FlowAssignMapper flowAssignMapper;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private NotifyMapper notifyMapper;

    /**
     * 内置
     */
    private final int BUILT_IN = 0;
    /**
     * 对外接口获取数据
     */
    private final int BUILT_OUT = 1;
    /**
     * 数据推送对方接口
     */
    private final int BUILT_PUSH = 2;

    /**
     * 新建操作
     */
    private static int create = 1;

    /**
     * 接收操作
     */
    private static int receive = 2;

    /**
     * 保存操作
     */
    private static int save = 3;

    /**
     * 转交操作
     */
    private static int turn = 4;

    /**
     * 委托操作
     */
    private static int intrust = 5;

    /**
     * 退回操作
     */
    private static int back = 6;
    //自动编号的计数器规则
    private final String COUNTER = "COUNTER";

    private static String document = "document";
    private static String attend_leave = "attend_leave";
    private static String attend_evection = "attend_evection";
    private static String attend_out = "attend_out";
    private static String budgeting_process = "budgeting_process";
    private static String edu_fixassets = "edu_fixassets";
    private static String addNotify = "save_notify";
    private static String fileContent = "save_fileContent";
    private static String party_member = "party_member";
    List<String> dataParentList = new ArrayList<>();
    List<String> dataSonList = new ArrayList<>();
    List<String> dataList = new ArrayList<>();
    //微信推送数据
    private TriggerPlugIn weChatTriggerPlugIn = new TriggerPlugIn();

    public ToJson<FlowFast> workFastAdd(Users users, Integer flowId, Integer prcsId, String flowPrcs, String id, HttpServletRequest request, String sqlType, String runName, String preView) {
        ToJson<FlowFast> tj = new ToJson<FlowFast>();
        try {

            //本部门
            Department dep = departmentService.getDeptById(users.getDeptId());
            //获取当前流程的转入和转出的条件判断以及回退条件判断以及工作流表单的样式
            FlowFast flowFast = this.conditionSetting(flowId, flowPrcs);
            //------------------wym-------------------
            //保密字段处理
            FlowProcess flowProcess = this.hidden(flowId, prcsId, users.getUserId(), id, flowPrcs);
            //关联操作设置
            if (flowProcess != null) {
                if (flowProcess.getOperationButton() != null && flowProcess.getOperationButton() != "") {
                    String[] operationButton = flowProcess.getOperationButton().split(",");
                    String operationButtonName = "";
                    for (int i = 0; i < operationButton.length; i++) {
                        operationButtonName = operationButtonName + flowOperationMapper.selectByPrimaryKey(Integer.parseInt(operationButton[i])).getOpName() + ",";
                    }
                    flowProcess.setOperationButtonName(operationButtonName);
                }
            }

            // 判断是否关联应用 关联的话 查询出应用的信息
            if (flowProcess != null && flowProcess.getRelationId() != null && flowProcess.getRelationId() != 0) {
                RelationFunc relationFunc = relationFuncMapper.selectByPrimaryKey(flowProcess.getRelationId());
                flowProcess.setRelationFunc(relationFunc);
            }
            flowFast.setFlowProcesses(flowProcess);
            //存储当前用户
            flowFast.setUserName(users.getUserName());

            //自动文号表达式
            String autoName = flowFast.getFlowTypeModel().getAutoName();

            if (StringUtils.checkNull(runName)) {
                if (StringUtils.checkNull(autoName)) {
                    runName = flowFast.getFlowTypeModel().getFlowName() + " " + DateFormat.getStrDate(new Date());
                }
            }
            FlowRunPrcs flowRunPrcs = null;
            FlowRun flowRun = null;

            String beginTime = DateFormat.getStrDate(new Date());
            //开始判断
            if (prcsId == 1 && StringUtils.checkNull(id)) {
                //查找流程实例基本信息
                flowRun = this.getRun(autoName, flowId, users, beginTime, flowFast.getFlowTypeModel(), dep, runName);
                int runId = flowRun.getRunId();
                flowRun.setUid(String.valueOf(users.getUid()));
                flowRun.setUserName(users.getUserName());
                flowRun.setEndTime("");
                flowRunPrcs = new FlowRunPrcs(runId, prcsId, users.getUserId(), beginTime, "0000-00-00 00:00:00", "2", 1, "1", "0", beginTime, "0000-00-00 00:00:00", users.getDeptId(), "0", "0");
                //flowRunPrcs.setParentPrcsId("0");
                flowRunPrcs.setBranchCount("0");
                wfeFlowRunPrcs.save(flowRunPrcs);
            } else {
                flowRun = wfeFlowRun.find(Integer.parseInt(id));
                if (StringUtils.checkNull(flowPrcs)) {
                    //查询最后一条数据
                    //flowRun = wfeFlowRun.find(Integer.parseInt(id));
                    Integer runId = flowRun.getRunId();
                    FlowRunPrcs flowRunPrcs1 = wfeFlowRunPrcs.getLastPrcsByRunId(runId);
                    Users u = usersService.getUsersByuserId(flowRun.getBeginUser());
                    flowRun.setUserName(u.getUserName());
                    flowFast.setFlowRun(flowRun);
                    flowFast.setFlowRunPrcs(flowRunPrcs1);
                    FlowProcess thisFp = this.wfeFlowProcess.findbyprcsId(flowId.intValue(), flowRunPrcs1.getFlowPrcs().intValue());
                    flowFast.setFlowProcesses(thisFp);
                    tj.setObject(flowFast);
                    tj.setMsg("只显示查询！");
                    tj.setFlag(0);
                    return tj;
                }
                //适应前端查询请求,判断是否存在此流程
                Map<String, Object> mapCheck = new HashMap<String, Object>();
                mapCheck.put("prcsId", prcsId);
                mapCheck.put("runId", id);
                mapCheck.put("flowPrcs", flowPrcs);
                List<FlowRunPrcs> checkFloRunPrcs = wfeFlowRunPrcs.findByRunId1(mapCheck);

                if (checkFloRunPrcs.size() > 0) {
                    for (FlowRunPrcs flowRunPrcs1 : checkFloRunPrcs) {

                        if (("1").equals(preView)) {
                            flowRun = wfeFlowRun.find(Integer.parseInt(id));
                            Users u = usersService.getUsersByuserId(flowRun.getBeginUser());
                            flowRun.setUserName(u.getUserName());
                            flowFast.setFlowRun(flowRun);
                            flowFast.setFlowRunPrcs(flowRunPrcs1);
                            //强制合并
                            if ("1".equals(flowProcess.getGatherNode())) {
                                Integer gatherNodePriv = this.reGatherNodePriv(String.valueOf(flowFast.getFlowRun().getRunId()), Integer.parseInt(flowPrcs), prcsId, users.getUserId());
                                flowFast.setGatherNodePriv(String.valueOf(gatherNodePriv));
                            } else {
                                flowFast.setGatherNodePriv(flowProcess.getGatherNode());
                            }
                            tj.setObject(flowFast);
                            tj.setMsg("只显示查询！");
                            tj.setFlag(0);
                            return tj;
                        }
                        if (users.getUserId().equals(flowRunPrcs1.getUserId())) {
                            if (Integer.parseInt(flowRunPrcs1.getPrcsFlag())== 3 ||Integer.parseInt(flowRunPrcs1.getPrcsFlag())== 4 ) {
                                flowRun = wfeFlowRun.find(Integer.parseInt(id));
                                flowRun.setUserName(users.getUserName());
                                flowFast.setFlowRun(flowRun);
                                flowFast.setFlowRunPrcs(flowRunPrcs1);
                                if ("1".equals(flowProcess.getGatherNode())) {
                                    Integer gatherNodePriv = this.reGatherNodePriv(String.valueOf(flowFast.getFlowRun().getRunId()), Integer.parseInt(flowPrcs), prcsId, users.getUserId());
                                    flowFast.setGatherNodePriv(String.valueOf(gatherNodePriv));
                                } else {
                                    flowFast.setGatherNodePriv(flowProcess.getGatherNode());
                                }
                                tj.setObject(flowFast);
                                tj.setMsg("已转交，不能再进行办理！");
                                tj.setFlag(0);
                                tj.setTurn(true);
                                return tj;
                            }
                        }
                    }
                }
                //判断是否允许传阅
                String isViewPriv = this.checkViewPriv(flowFast.getFlowTypeModel().getViewPriv(), flowProcess.getViewPriv());
                flowFast.setIsViewPriv(isViewPriv);
                List<Users> listView = new ArrayList<Users>();
                //可传阅用户
                if (("1").equals(isViewPriv)) {

                    SysPara sysPara = sysParaMapper.querySysPara("MYPROJECT");
                    String paraName = null;
                    if (null != sysPara) {
                        paraName = sysPara.getParaValue();
                    }

                    if (1 == prcsId || !"dazu".equals(paraName)) {
                        listView = usersService.reAllPrivUser(flowFast.getFlowTypeModel().getViewUser(), flowFast.getFlowTypeModel().getViewDept(), flowFast.getFlowTypeModel().getViewRole());
                    } else {
                        if (!StringUtils.checkNull(flowRun.getViewUser())) {
                            listView = usersService.getUserByuserId(flowRun.getViewUser());
                        }
                    }

                    // listView = usersService.reAllPrivUser(flowFast.getFlowTypeModel().getViewUser(), flowFast.getFlowTypeModel().getViewDept(), flowFast.getFlowTypeModel().getViewRole());
                    flowFast.setListView(listView);
                }
                //所有传阅用户的姓名
                String viewUser = usersService.reAllName(listView);
                //是否允许会签
                String feedback = flowProcess.getFeedback();
                flowFast.setFeedback(feedback);
                //公共附件中的Office文档详细权限设置：(1-新建权限,2-编辑权限,3-删除权限,4-下载权限,5-打印权限,)
                flowFast.setAttachPriv(flowProcess.getAttachPriv());
                //文号是否可编辑
                flowFast.setIsWorkName(this.workName(flowProcess));

                //查找流程实例基本信息
                flowRun = wfeFlowRun.find(Integer.parseInt(id));
                //应对非空
                if (StringUtils.checkNull(flowRun.getEndTime())) {
                    flowRun.setEndTime("");
                }
                Users users1 = usersService.getUsersByuserId(flowRun.getBeginUser());


                flowRun.setUid(String.valueOf(users1.getUid()));
                flowRun.setUserName(users1.getUserName());
                Map<String, Object> m = new HashMap<String, Object>();
                m.put("runId", id);
                m.put("prcsId", prcsId);

                m.put("prcsTime", DateFormat.getStrDate(new Date()));
                m.put("flowPrcs", flowPrcs);

                List<FlowRunPrcs> listFloRunPrcs = null;
                //查询当前flow_run_prcs中的topFlag值
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("userId", users.getUserId());
                map.put("runId", flowRun.getRunId());
                map.put("prcsId", prcsId);
                map.put("flowPrcs", flowPrcs);
                List<FlowRunPrcs> flowRunPrcs1 = wfeFlowRunPrcs.findByRunIdTopFlag(map);
                //如果当前集合为空说明该流程为新建流程
                if (flowRunPrcs1.size() > 0) {
                    //先接收者主办
                    if ("1".equals(flowRunPrcs1.get(0).getTopFlag())) {
                        synchronized (this) {
                            m.put("opFlag", 1);
                            listFloRunPrcs = wfeFlowRunPrcs.selectCondition(m);
                            if (listFloRunPrcs.size() > 1) {
                                // m.put("userId", userId);
                                m.put("opFlag", 0);
                                wfeFlowRunPrcs.updateOpflag(m);
                                m.put("opFlag", 1);
                                m.put("userId", users.getUserId());
                                wfeFlowRunPrcs.updateOpflag(m);
                                String smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + prcsId + "&runId=" + flowRun.getRunId() + "&prcsId=" + flowPrcs;
                                m.put("type", 7);
                                m.put("id", smsUrl.trim());
                                List<Sms> smsList = smsMapper.querySmsByTypeAll(m);
                                SmsBody smsBody = new SmsBody();
                                for (Sms sms : smsList) {
                                    if (!sms.getToId().equals(users.getUserId())) {
                                        smsUrl = "/workflow/work/workform?opflag=0&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + prcsId + "&runId=" + flowRun.getRunId() + "&prcsId=" + flowPrcs;
                                        smsBody.setRemindUrl(smsUrl);
                                        smsBody.setBodyId(sms.getBodyId());
                                        smsBody.setSmsType("7");
                                        smsBodyMapper.updateByPrimaryKeySelective(smsBody);
                                    }
                                }
                            }
                            m.remove("opFlag");
                            m.put("userId", users.getUserId());
                            listFloRunPrcs = wfeFlowRunPrcs.selectCondition(m);
                            flowRunPrcs = listFloRunPrcs.get(0);
                        }

                    } else if ("2".equals(flowRunPrcs1.get(0).getTopFlag())) {
                        m.put("opFlag", 0);
                        m.put("prcsFlag", "sign");
                        listFloRunPrcs = wfeFlowRunPrcs.selectCondition(m);
                        m.remove("prcsFlag");
                        if (listFloRunPrcs != null && listFloRunPrcs.size() == 1) {
                            flowRunPrcs = listFloRunPrcs.get(0);
                            flowRunPrcs.setOpFlag("1");
                        } else {
                            m.put("userId", users.getUserId());
                            m.put("opFlag", null);
                            m.put("prcsFlag", null);
                            listFloRunPrcs = wfeFlowRunPrcs.selectCondition(m);
                            if (listFloRunPrcs.size() == 0 || listFloRunPrcs == null) {
                                m.put("userId", null);
                                listFloRunPrcs = wfeFlowRunPrcs.selectCondition(m);
                            }
                            flowRunPrcs = listFloRunPrcs.get(0);
                        }
                    } else { //该流程为新建流程
                        m.put("userId", users.getUserId());
                        m.put("opFlag", null);
                        m.put("prcsFlag", null);
                        listFloRunPrcs = wfeFlowRunPrcs.selectCondition(m);
                        flowRunPrcs = listFloRunPrcs.get(0);
                    }
                    if (Integer.parseInt(flowRunPrcs.getPrcsFlag()) < 2) {
                        //更新当前流程状态
                        m.put("prcsFlag", "2");
                        //区分无主办人办理情况（已办/待办）
                        if (!users.getUserId().equals(flowRunPrcs.getUserId())) {
                            m.put("userId", flowRunPrcs.getUserId());
                        } else {
                            m.put("userId", users.getUserId());
                        }
                        wfeFlowRunPrcs.updateSql(m);
                        m.put("prcsFlag", "4");
                        m.put("prcsId", prcsId - 1);
                        m.remove("prcsTime");
                        String parent = flowRunPrcs.getParent();
                        m.put("flowPrcs", parent);
                        m.remove("userId");
                        m.remove("opFlag");

                        String[] parents = parent.split(",");
                        if (parents.length > 1 && !StringUtils.checkNull(flowRunPrcs.getBranchCount())) {
                            //兼容branch——count
                            if (flowRunPrcs.getBranchCount().length() > 1) {
                                String aString = parent.substring(0, 1);
                                m.put("flowPrcs", aString);
                                wfeFlowRunPrcs.updateSql(m);
                            } else {
                                m.put("branchCount", flowRunPrcs.getBranchCount());
                                // wfeFlowRunPrcs.updateParentPrcsFlag(m);
                            }
                        } else {
                            //判断转交的父步骤主办人是否办理完毕，如主办人未办理完毕。则是转交时勾选了复选框（本步骤转交下一步但不结束办理）
                            //反之，属于正常流转
                            Map<String, Object> maps = new HashMap<>();
                            maps.put("flowPrcs", parent);
                            maps.put("prcsId", prcsId - 1);
                            maps.put("runId", flowRun.getRunId());
                            List<FlowRunPrcs> frp2 = wfeFlowRunPrcs.selectFind(maps);
                            for (FlowRunPrcs frp : frp2) {
                                if (("1").equals(frp.getOpFlag()) && Integer.parseInt(frp.getPrcsFlag()) >= 3) {
                                    wfeFlowRunPrcs.updateSql(m);
                                    break;
                                }
                            }
                        }
                        //并发则parent会有多个
                      /*  String aString = parent.substring(parent.indexOf(",") + 1, parent.length());
                        m.put("flowPrcs", aString);
                        m.remove("userId");
                        m.remove("opFlag");
                        wfeFlowRunPrcs.updateSql(m);*/
                        try {
                            //查看当前流程的父流程实例：唯一
                            Map parentMap = new HashMap();
                            parentMap.put("childRun", id);
                            FlowRunPrcs parentFlowRunPrcs = flowRunPrcsMapper.selectParentFlowRunPrcs(parentMap);
                            if (parentFlowRunPrcs != null) {
                                FlowRunPrcs flowRunPrcs2 = new FlowRunPrcs();
                                parentMap.put("prcsFlag", '2');
                                parentMap.put("prcsTime", DateFormat.getStrDate(new Date()));
                                parentMap.put("id", parentFlowRunPrcs.getId());
                                flowRunPrcsMapper.updateFlowPrcs(parentMap);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
                //flowRunPrcs = this.topDefault(listFloRunPrcs, users.getUserId(), flowProcess.getTopDefault(), m);
            }
            flowFast.setFlowRun(flowRun);
            flowFast.setFlowRunPrcs(flowRunPrcs);
            if ("1".equals(flowProcess.getGatherNode())) {
                // Integer gatherNodePriv = this.reGatherNodePriv(String.valueOf(flowFast.getFlowRun().getRunId()), Integer.parseInt(flowPrcs), users.getUserId(), flowId);
                //Integer gatherNodePriv = this.reGatherNodePriv(String.valueOf(flowFast.getFlowRun().getRunId()), Integer.parseInt(flowPrcs), prcsId, users.getUserId());
                flowFast.setGatherNodePriv("0");
            } else {
                flowFast.setGatherNodePriv(flowProcess.getGatherNode());
            }
            //经办人未办理完毕时是否允许主办人强制转交
            Map<String, Object> mC = new HashMap<String, Object>();
            mC.put("prcsId", prcsId);
            mC.put("runId", id);
            mC.put("flowPrcs", flowPrcs);
            mC.put("userId", users.getUserId());
            if ("1".equals(flowProcess.getTurnPriv()) || "2".equals(flowRunPrcs.getTopFlag())) {
                flowFast.setCheckTurnPriv("1");
            } else {
                //查询经办流程
                List<FlowRunPrcs> checkOp = wfeFlowRunPrcs.selectOp(mC);
                if (checkOp != null) {
                    flowFast.setCheckTurnPriv("1");
                    for (FlowRunPrcs flowRunPrcs1 : checkOp) {
                        if (!"4".equals(flowRunPrcs1.getPrcsFlag())) {
                            flowFast.setCheckTurnPriv("0");
                        }
                    }
                }
                //返回经办流程
                flowFast.setListTurnPriv(checkOp);
            }
            tj.setObject(flowFast);
            tj.setMsg("OK");
            tj.setFlag(0);
        } catch (Exception e) {
            tj.setMsg(e.getMessage());
            tj.setFlag(1);
            e.printStackTrace();
        }
        return tj;
    }


    public FlowRunPrcs topDefault(List<FlowRunPrcs> listFloRunPrcs, String userId, String topDefault, Map<String, Object> m) {
        FlowRunPrcs flowRunPrcs = null;
        synchronized (this) {
            if (listFloRunPrcs.size() > 1) {
                if ("1".equals(topDefault)) {
                    // m.put("userId", userId);
                    m.put("opFlag", 0);
                    wfeFlowRunPrcs.updateOpflag(m);
                    m.put("opFlag", 1);
                    m.put("userId", userId);
                    wfeFlowRunPrcs.updateOpflag(m);
                }
            }

        }
        for (FlowRunPrcs flowRunPrcs1 : listFloRunPrcs) {
            if (userId.equals(flowRunPrcs1.getUserId())) {
                flowRunPrcs = flowRunPrcs1;
            }
        }
        return flowRunPrcs;
    }


    //保密字段处理
    public FlowProcess hidden(Integer flowId, Integer prcsId, String userId, String id, String flowPrcs) {
        Map<String, FlowProcess> map = new HashMap<String, FlowProcess>();
        FlowProcess flowProcess = new FlowProcess();
        //存储所有流程
        map = this.allflowProcessBymap(flowId);
        //当前流程
        flowProcess = map.get(flowPrcs);
        String prcsid = String.valueOf(prcsId);
        //说明该流程步骤数大于1 wym
        if (!"1".equals(prcsid) && !"".equals(id) && !"0".equals(prcsid)) {
            //根据FlowId和流程实runId查询FlowProcess
            map = this.queryFlowProcessUserId(flowId, Integer.valueOf(id));
            //取出先前步骤的保密字段
            String hiddenItemStr = flowProcess.getHiddenItem();
            //遍历所有流程
            Iterator<Map.Entry<String, FlowProcess>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, FlowProcess> entry = it.next();
                //判断之前步骤是否与该步骤转交人一致
                if (userId.equals(entry.getValue().getUserId())) {
                    //转交人一致的保密字段
                    String hiddenTempStr = entry.getValue().getHiddenItem();
                    String[] str = hiddenTempStr.split(",");
                    //如果一致，将保密字段拼接返给前台
                    for (int i = 0; i < str.length; i++) {
                        if (StringUtils.checkNull(hiddenItemStr)) {
                            hiddenItemStr = str[i] + ",";
                        } else if (hiddenItemStr.indexOf(str[i]) == -1) {
                            if (",".equals(hiddenItemStr.substring(hiddenItemStr.length() - 1))) {
                                hiddenItemStr += str[i];
                            } else {
                                hiddenItemStr += "," + str[i];
                            }
                        }
                    }
                }
            }
            flowProcess.setHiddenItem(hiddenItemStr);
            // -----------wym--
        }

        return flowProcess;
    }


    public ToJson<FlowFast> nextwork(Integer flowId, String formdata, String modifydata, String formlength, int runId,
                                     String runName, String beginTime, String beginUser, String sqlType, String prcsId, String fromDateReject, String tableNameother, String tabId,
                                     String flowPrcs, HttpServletRequest request) {

        /**  lr添加工作流程使用日志--保存  **/
        FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
        flowRunLog.setType(Constant.TYPE2);
        flowRunLog.setRunId(runId);
        flowRunLog.setFlowPrcs(Integer.parseInt(flowPrcs));
        flowRunLog.setPrcsId(Integer.parseInt(prcsId));
        wfeLog.addFlowRunLog(flowRunLog);
        //工作等级修改
        String workLevel = request.getParameter("workLevel");
        //会签控件保存采用追加方式,会签控件对应data_数值
        String countersignData = request.getParameter("countersignData");
        //获取到sysRule对应的id
        String sysIds = request.getParameter("sysIds");
        JSONArray json = new JSONArray();
        Map sysIdsMap = json.parseObject(sysIds, Map.class);


        Map<String, Object> mwl = new HashMap<String, Object>();
        mwl.put("runId", runId);
        if (StringUtils.checkNull(workLevel)) {
            mwl.put("workLevel", 0);
        } else {
            mwl.put("workLevel", workLevel);
        }
        //文号修改
        mwl.put("runName", runName);
        wfeFlowRun.updateState(mwl);
        //更新公文标题
        documentSerivce.updateDocumentTitle(runName,runId);
        //解决异常输入'
        formdata = formdata.replace("null", "");
        modifydata = modifydata.replace("null", "");


        ToJson<FlowFast> tj = new ToJson<FlowFast>();
        //用来存储sql传入参数
        Map<String, Object> param = new HashMap();
        // JSONArray json = new JSONArray();

        String tableName = "flow_data_" + flowId;
        //表单上所有的数据
        List<Map<String, Object>> l = JSONArray.parseObject(formdata, List.class);
        //用来存储表单上所有的数据
        List<Map<String, Object>> lAll = new ArrayList<Map<String, Object>>();
        //处理异常数据,前台传入参数可能为空
        for (int i = 0; i < l.size(); i++) {
            if (l.get(i).size() == 2 && (String) l.get(i).get("key") != ""&&checkNum((String) l.get(i).get("key"))) {
                lAll.add(l.get(i));
            }
        }
        //此段代码只为添加对前端传入参数的异常处理
        List<String> keyc = new ArrayList<String>();
        for (Map<String, Object> map : l) {
            if (keyc.contains(map.get("key"))) {
                tj.setMsg("There are duplicate fields in the form parameter!" + map.get("key"));
                tj.setFlag(1);
                return tj;
            }
            keyc.add((String) map.get("key"));
        }

        List<Map<String, Object>> modify = JSONArray.parseObject(modifydata, List.class);
        List<Map<String, Object>> mAll = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < modify.size(); i++) {
            if (modify.get(i).size() == 2) {
                mAll.add(modify.get(i));
            }
        }
        //StringBuffer sbcreate = new StringBuffer();

        List<FlowFormType> allFlowForm = wfeFormTypeMapper.getFrombyFlowId(flowId);
        FlowFormType flowFormType = allFlowForm.get(0);
        //获取表单信息
        Document document = HtmlUtil.getDom(flowFormType.getPrintModel());
        try {
            //获取该表数据库中的所有的列
            List<String> columns = this.createTable(tableName, sqlType, lAll);
            if (columns.size() > 0) {
                //用于存储数据库插入的字段
                List<String> key = new ArrayList<String>();
                //用于存储新增字段
                List<String> unusual = new ArrayList<String>();
                //用于获取传入表单上的所有key值
                List<String> Allkey = new ArrayList<String>();
                //用于存储已删除字段
                List<String> delkey = new ArrayList<String>();
                //遍历表单数据获取新增字段和所有
                for (Map<String, Object> map : lAll) {
                    String keyBd = (String) map.get("key");
                    String keyBdvalue = ((String) map.get("value")).replace(" ", "");//去除空格
                    String documentDataType = HtmlUtil.getDocumentDataType(document, keyBd);
                    if ("autocode".equals(documentDataType) && sysIdsMap != null && !keyBdvalue.endsWith("{autocode}") && !StringUtils.checkNull(keyBdvalue)) {
                        String sysId = (String) sysIdsMap.get(keyBd);
                        SysRuleModel sysRuleModel = new SysRuleModel();
                        sysRuleModel.setId(sysId);
                        SysRuleModel ruleById = documentSerivce.getRuleById(sysRuleModel, request);
                        // 定义正则表达式
                        Pattern pattern = Pattern.compile("(?<=\\[)(.+?)(?=\\])");
                        String expression = ruleById.getExpression();
                        Matcher matcher = pattern.matcher(expression);
                        //判断是否含有计数器规则
                        while (matcher.find()) {
                            switch (matcher.group()) {
                                // 获取计数器
                                case COUNTER:
                                    //[COUNTER]前的规则
                                    String jiequ = expression.substring(0, expression.indexOf("[COUNTER]"));
                                    //[COUNTER]后的规则
                                    String after = expression.substring(jiequ.length() + 9, expression.length());
                                    int before = (documentSerivce.rule(jiequ).replace(" ", "")).length();
                                    int end = (documentSerivce.rule(after).replace(" ", "")).length();
                                    String strm2 = keyBdvalue.substring(before, keyBdvalue.length() - end);
                                    Pattern par = Pattern.compile("^[-\\+]?[\\d]*$");
                                    if (par.matcher(strm2).matches()) {
                                        if (ruleById.getCounter() <= Integer.parseInt(strm2.trim())) {
                                            ruleById.setCounter(Integer.parseInt(strm2.trim()));
                                            documentSerivce.updateRuleById(ruleById);
                                        }
                                    } else {
                                        tj.setMsg("自动编号规则不符合");
                                        tj.setFlag(1);
                                        return tj;
                                    }
                                    break;
                            }
                        }
                    }
                    if (!columns.contains(keyBd.toUpperCase())) {
                        if (!StringUtils.checkNull((String) map.get("key"))) {
                            //添加新增的表字段
                            unusual.add((String) map.get("key"));
                        }
                    }
                    //获取所有表单传入键值
                    Allkey.add((String) map.get("key"));
                }
                //移除数据库中非DATA开头的数据
                Iterator<String> it = columns.iterator();
                while (it.hasNext()) {
                    String x = it.next();
                    if (!x.toUpperCase().contains("DATA")) {
                        it.remove();
                    }
                }
                //存储表单可能删除的列
                for (int i = 0; i < columns.size(); i++) {
                    if (!Allkey.contains(columns.get(i))) {
                        delkey.add(columns.get(i));
                    }
                }
                //添加表的列
                if (unusual.size() > 0) {
                    param.put("tableName", tableName);
                    param.put("keys", unusual);
                    workMapper.addcolumn(param);
                }

                Map<String, Object> maps = new HashMap<String, Object>();
                maps.put("tableName", tableName);
                maps.put("runId", runId);
                //查询该表单的信息
                Map<String, Object> m = workMapper.select(maps);
                key = new ArrayList<String>();
                List<Object> value = new ArrayList<Object>();


                if (m == null || m.size() == 0) {
                    key.add("RUN_ID");
                    value.add(String.valueOf(runId));
                    key.add("RUN_NAME");
                    value.add(runName);
                    key.add("BEGIN_TIME");
                    value.add(beginTime);
                    key.add("BEGIN_USER");
                    value.add(beginUser);

                    FlowTypeModel flowTypeModel = wfeFlowTypeModelMapper.queryOneObject(flowId);
                    if (flowTypeModel.getAutoNum() != null && flowTypeModel.getAutoNum() != 0) {
                        Integer flowAutoNum = flowTypeModel.getAutoNum();
                        key.add("FLOW_AUTO_NUM");
                        value.add(flowAutoNum);
                    }

                 /*   key.add("FLOW_AUTO_NUM");
                    value.add(0);
                    key.add("FLOW_AUTO_NUM_YEAR");
                    value.add(0);
                    key.add("FLOW_AUTO_NUM_MONTH");
                    value.add(0);*/

                    //第一次不能根据此判断
                  /*  List<String> listmodify = new ArrayList<String>();
                    for (Map<String, Object> mapmodify : modify) {
                        key.add((String) mapmodify.get("key"));
                        value.add((String) mapmodify.get("value"));
                        listmodify.add((String) mapmodify.get("key"));
                    }*/
                    /*for (Map<String, Object> map : l) {
                        if (!listmodify.contains((String) map.get("key"))) {
                            key.add((String) map.get("key"));
                            value.add("");
                        }
                    }*/

                    for (Map<String, Object> map : lAll) {
                        key.add((String) map.get("key"));
                        value.add((String) map.get("value"));
                        String size = (String) map.get("value");
                        int length = size.length();
                        if (length > 65500) {
                            maps.put("modifyKey", (String) map.get("key"));
                            workMapper.modifyColumn(maps);
                        }

                    }

                    //表单可能删除的列
                    for (String s : delkey) {
                        key.add(s);
                        value.add("");
                    }
                    param.put("tableName", tableName);
                    param.put("keys", key);
                    param.put("values", value);
                    workMapper.insert(param);
                } else {
                    if (mAll.size() != 0) {
                        Map<String, Object> countersignDataMap = null;
                        if (!StringUtils.checkNull(countersignData)) {
                            //参数处理，防止sql注入
                            List<String> dataList = new ArrayList<>(Arrays.asList(countersignData.split(",")));
                            dataList.removeIf(s->!checkNum(s));
                            countersignDataMap = workMapper.getDataValue(dataList, runId, tableName);
                        }

                        for (Map<String, Object> map : mAll) {
                            String key1 = map.get("key").toString();
                            String value1 = map.get("value").toString();
                            value1 = value1.replace("'", "\\'");

                            //判断是会签控件且数据库有值
                            if (countersignDataMap != null && countersignDataMap.containsKey(key1)&&!countersignDataMap.get(key1).toString().equals("")) {
                               // key.add(key1 + "=" + "'" + countersignDataMap.get(key1) + value1 + "'");//现在改为意见可以删除
                                //key.add(key1 + "=" + "'" + value1 + "'");
                                //  key.add(key1 + "=" + "'" + countersignDataMap.get(key1) + value1 + "'");//现在改为意见可以删除

                                //判断审批意见控件是否有值
                                if(null!=value1&&!value1.equals("")){

                                    Document documentShuJuKu=Jsoup.parse(countersignDataMap.get(key1).toString());
                                    Elements eiderareaShuJuKu = documentShuJuKu.getElementsByClass("eiderarea");

                                    //表单填写传来的的审批意见
                                    Document documentFrom=Jsoup.parse(value1);
                                    String user_idFrom = documentFrom.getElementsByClass("eiderarea").last().attr("user_id");
                                    String prcs_idFrom = documentFrom.getElementsByClass("eiderarea").last().attr("prcs_id");
                                    if(!value1.equals("")&&!user_idFrom.equals("")&&!prcs_idFrom.equals("")){
                                        //遍历添加数据库意见
                                        LinkedList<String> linkedList=new LinkedList<>();
                                        for(Element element: eiderareaShuJuKu){
                                            linkedList.addLast(element.toString());
                                        }

                                        //替换意见
                                        //数据库最后一个人的审批意见
                                       Document documentShuJuKuM=Jsoup.parse(linkedList.getLast());
                                        String user_idFromM = documentShuJuKuM.getElementsByClass("eiderarea").eq(0).attr("user_id");
                                        String prcs_idFromM = documentShuJuKuM.getElementsByClass("eiderarea").eq(0).attr("prcs_id");
                                        if(user_idFromM.equals(user_idFrom)&&prcs_idFrom.equals(prcs_idFromM)){
                                            linkedList.removeLast();
                                            linkedList.addLast(value1);
                                        }else {
                                            linkedList.addLast(value1);
                                        }


                                        /*//替换意见-按照流程步骤进行排列
                                        int prcs_idFrom_int = Integer.parseInt(prcs_idFrom);
                                        for(int i=0;i<linkedList.size();i++){
                                            Document documentShuJuKu2=Jsoup.parse(linkedList.get(i));
                                            String user_idFrom2 = documentShuJuKu2.getElementsByClass("eiderarea").eq(0).attr("user_id");
                                            String prcs_idFrom2 = documentShuJuKu2.getElementsByClass("eiderarea").eq(0).attr("prcs_id");
                                            if(user_idFrom2.equals("")&&prcs_idFrom2.equals("")){
                                                linkedList.addLast(value1);
                                                break;
                                            }else{
                                                int y=i;
                                                if((y+1)<linkedList.size()){
                                                    y++;
                                                }
                                                Document documentShuJuKu3=Jsoup.parse(linkedList.get(y));
                                                String user_idFrom3 = documentShuJuKu3.getElementsByClass("eiderarea").eq(0).attr("user_id");
                                                String prcs_idFrom3 = documentShuJuKu3.getElementsByClass("eiderarea").eq(0).attr("prcs_id");
                                                int prcs_idFrom2_int = Integer.parseInt(prcs_idFrom2);
                                                int prcs_idFrom3_int = Integer.parseInt(prcs_idFrom3);
                                                if(user_idFrom2.equals(user_idFrom)&&prcs_idFrom2_int==prcs_idFrom_int){
                                                    linkedList.set(i,value1);
                                                    break;
                                                }else if(user_idFrom3.equals(user_idFrom)&&prcs_idFrom3_int==prcs_idFrom_int){
                                                    linkedList.set(y,value1);
                                                    break;
                                                }else if(prcs_idFrom2_int<prcs_idFrom_int&&prcs_idFrom3_int>prcs_idFrom_int){
                                                    linkedList.add(y,value1);
                                                    break;
                                                }else if(i==y){
                                                    linkedList.addLast(value1);
                                                    break;
                                                }
                                            }
                                        }*/

                                        //拼接

                                        StringBuilder stringBuilder=new StringBuilder();
                                        for (int i=0;i<linkedList.size();i++){

                                            stringBuilder.append(linkedList.get(i));
                                        }
                                        key.add(key1 + "=" + "'" + stringBuilder.toString() + "'");
                                    }

                                }
                            } else {
                                key.add(key1 + "=" + "'" + value1 + "'");
                            }
                            String size = (String) map.get("value");
                            int length = size.length();
                            if (length > 65500) {
                                maps.put("modifyKey", (String) map.get("key"));
                                workMapper.modifyColumn(maps);
                            }
                        }
                        param.put("tableName", tableName);
                        param.put("keys", key);
                        param.put("runId", String.valueOf(runId));
                        workMapper.update(param);
                    }
                }
            }
            tj.setMsg("OK");
            tj.setFlag(0);
            //保存成功检索有没有插件,如果有，执行插件
            try {
                workFlowPlugin.plugin(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            tj.setFlag(1);
            tj.setMsg(e.getMessage());
            L.e("work nextwork:" + e);
        }
        return tj;
    }


    public ToJson<FlowRunPrcs> saveworkyuan(String runId, String runName, String flowId, String prcsId, String prcsFlag, String flowStep,
                                            String flowPrcs, String beginTime, String beginUser, String jingbanUser, String viewUser, Users users, String currentPrcsId, String topDefault, String tabId, String branchCount) {

        ToJson<FlowRunPrcs> toJson = new ToJson<FlowRunPrcs>();
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("prcsId", Integer.parseInt(prcsId));
        maps.put("runId", Integer.parseInt(runId));
        maps.put("prcsFlag", "3");
        maps.put("deliverTime", DateFormat.getStrDate(new Date()));
        maps.put("userId", users.getUserId());

        //String branchc = "";2692
        //应对并发
        if (!flowPrcs.contains(",")) {
            //强制合并节点不存branchCount
            if (!"0".equals(flowPrcs)) {
                //FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(Integer.parseInt(flowId), Integer.parseInt(flowPrcs));
                maps.put("prcsId", Integer.parseInt(prcsId) - 1);
                List<FlowRunPrcs> flowRunPrcs = wfeFlowRunPrcs.findByRunId(maps);
                maps.put("prcsId", Integer.parseInt(prcsId));
                maps.put("flowPrcs", currentPrcsId);
                //存并发节点
                FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(Integer.parseInt(flowId), Integer.parseInt(flowPrcs));
                if ("1".equals(flowProcess.getGatherNode())) {
                    branchCount = this.getBranchCount(flowRunPrcs, branchCount, "");
                } else {
                    branchCount = this.getBranchCount(flowRunPrcs, branchCount, flowPrcs);
                }
            }
        }
        if (!StringUtils.checkNull(branchCount)) {
            maps.put("branchCount", branchCount);//并发多个步骤
        }
        maps.put("flowPrcs", currentPrcsId);
        wfeFlowRunPrcs.updateSql(maps);

        //强制转交处理经办人流程状态
        maps.put("prcsFlag", "4");
        //maps.put("deliverTime", DateFormat.getStrDate(new Date()));
        //更新
        maps.remove("userId");
        //步骤对应流程信息
        FlowProcess f = wfeFlowProcess.findbyprcsId(Integer.parseInt(flowId), Integer.parseInt(currentPrcsId));
        if ("2" != (f.getTopDefault())) {
            maps.put("flowPrcs", currentPrcsId);
            wfeFlowRunPrcs.updateHandle(maps);
        }
        maps.put("prcsTime", DateFormat.getStrDate(new Date()));
        FlowRunPrcs fl = new FlowRunPrcs();
        // 添加传阅
        FlowRun flowRun = wfeFlowRun.find(Integer.valueOf(runId));
        if (flowRun != null) {
            if (!StringUtils.checkNull(viewUser)) {
                //修改传阅人
                flowRun.setViewUser(viewUser);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("runId", runId);
                map.put("viewUser", viewUser);
                wfeFlowRun.updateState(map);
                String[] viewUserStr = viewUser.split(",");
                Date date = new Date();
                for (String s : viewUserStr) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateStr = sdf.format(date);
                    Map map2 = new HashMap();
                    map2.put("runId", runId);
                    map2.put("userId", s);
                    map2.put("readDate", "0000-00-00 00:00:00");
                    map2.put("createDate", dateStr);
                    map2.put("readFlag", 0);
                    map2.put("prcsId", prcsId);
                    map2.put("flowPrcs", currentPrcsId);
                    if (!StringUtils.checkNull(tabId)) {
                        map2.put("tableId", tabId);
                    }
                    toBeReadMapper.insertFlowRunRead(map2);
                }
            }
        }

        /**     lr 工作流使用日志 ---转交**/
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        if (StringUtils.checkNull((String) request.getSession().getAttribute(
                "loginDateSouse"))) {
            sqlType = "xoa1001";
        }
        //触发器参数提取处公共方法
        TriggerPlugIn triggerPlugIn = this.getTrigger(runId, flowId, sqlType, beginUser, beginTime, runName, flowPrcs, prcsId, currentPrcsId, tabId, request, turn);
        //触发器执行
        this.notifyNotice(triggerPlugIn);
        //触发器 转发公告后将公告ID传给前端
        toJson.setObj1(triggerPlugIn.getNotifyId());
        //流程结束
        if (("0").equals(flowPrcs)) {

            Map<String, Object> updateSatus = new HashMap<String, Object>();
            updateSatus.put("prcsId", prcsId);
            updateSatus.put("runId", runId);
            updateSatus.put("prcsFlag", "4");
            updateSatus.put("userId", users.getUserId());
            updateSatus.put("flowPrcs", currentPrcsId);
            wfeFlowRunPrcs.updateSql(updateSatus);
            //获取该步骤所有流程
            List<FlowRunPrcs> datas = wfeFlowRunPrcs.getFlowRunReacsAllByRunId(runId);
            boolean flag = true;
            for (FlowRunPrcs flowRunPrcs : datas) {
                if (Integer.parseInt(flowRunPrcs.getPrcsFlag()) < 3) {
                    flag = false;
                    break;
                }
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("endTime", DateFormat.getStrDate(new Date()));
            map.put("runId", runId);
            if (flag) {
                wfeFlowRun.updateState(map);
            }
            try {
                newFlowRun(f, runId, users.getUserId());
                if (runId != null && !("").equals(runId.trim())) {
                    Map<String, Object> parentMap = new HashMap<>();
                    parentMap.put("childRun", runId);
                    FlowRunPrcs flowRunPrcs = flowRunPrcsMapper.selectParentFlowRunPrcs(parentMap);
                    if (flowRunPrcs != null) {
                        //拥有父流程，办结此步骤
                        parentMap.put("prcsFlag", "3");
                        parentMap.put("runId", flowRunPrcs.getRunId());
                        parentMap.put("prcsId", flowRunPrcs.getPrcsId());
                        parentMap.put("flowPrcs", flowRunPrcs.getFlowPrcs());
                        parentMap.put("deliverTime", DateFormat.getStrDate(new Date()));
                        wfeFlowRunPrcs.updateSql(parentMap);
                    }


//                    FlowRun flowRunSon = flowRunMapper.find(Integer.parseInt(runId));
//                    if (flowRunSon.getParentRun() != 0) {
//                        overMotion(runId);
//                        //添加子到父映射
//                        sonParent(flowRunSon);
//                    }
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                toJson.setObject(fl);
                toJson.setMsg("OK");
                toJson.setFlag(0);
                // HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
                FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
                flowRunLog.setType(Constant.TYPE11);

            } catch (Exception e) {
                toJson.setMsg(e.getMessage());
                L.e("work saveWork:" + e);
            }
            return toJson;
        }
        //下一步经办步骤
        String[] fpArray = flowPrcs.split(",");
        //经办人数组
        String[] alljingbanArray = jingbanUser.split("\\|");
        //主办人数组
        String[] beginUserArray = beginUser.split(",");
        //主办人相关选项数组
        String[] topDefaultArray = topDefault.split(",");


        for (int i = 0; i < fpArray.length; i++) {
            //步骤对应流程信息
            FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(Integer.parseInt(flowId), Integer.parseInt(fpArray[i]));

            String[] jingbanArray = null;
            //对应步骤经办数组
            jingbanArray = alljingbanArray[i].split(",");
            //判断该步骤是否是主办

            String beginByUser = null;
            if (!"2".equals(topDefaultArray[i])) {
                if (beginUserArray.length == 1) {
                    if (!StringUtils.checkNull(beginUserArray[0])) {
                        beginByUser = beginUserArray[0];
                    }
                } else if (beginUserArray.length == 0) {

                } else {
                    beginByUser = beginUserArray[i];
                }
            } else if ("2".equals(topDefaultArray[i])) {//无主办人办理
                if (jingbanArray.length > 0) {
                    //可能是无主办人有一个或多个
                    for (int j = 0; j < jingbanArray.length; j++) {
                        beginByUser += jingbanArray[j] + ",";
                    }
                    String str = beginByUser.substring(beginByUser.length() - 1, beginByUser.length());
                    if (",".equals(str)) {
                        beginByUser = beginByUser.substring(0, beginByUser.length() - 1);
                    }
                }
            }
            for (int j = 0; j < jingbanArray.length; j++) {

                Integer child_run = null;
                fl = new FlowRunPrcs();
                //添加先接收着者主办
                if ("1".equals(topDefaultArray[i])) {
                    fl.setOpFlag("1");
                } else if ("2".equals(topDefaultArray[i])) {  //无主办人会签
                    fl.setOpFlag("0");
                } else {
                    if (StringUtils.checkNull(beginByUser)) {
                        fl.setOpFlag("1");
                    } else {
                        if (beginByUser.equals(jingbanArray[j])) {
                            fl.setOpFlag("1");
                            //添加子流程
                            try {
                                FlowProcess flowProcesscurrent = wfeFlowProcess.findbyprcsId(Integer.parseInt(flowId), Integer.parseInt(fpArray[i]));
                                child_run = newFlowRun(flowProcesscurrent, runId, jingbanArray[j]);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            fl.setOpFlag("0");
                        }
                    }
                }
                if (child_run != null) {
                    //当前流程添加此子流程
                    fl.setChildRun(child_run);
                }
                fl.setTopFlag(topDefaultArray[i]);
                fl.setRunId(Integer.parseInt(runId));
                fl.setPrcsId(Integer.parseInt(prcsId) + 1);
                fl.setPrcsFlag("1");
                fl.setFlowPrcs(Integer.parseInt(fpArray[i]));
                //查看是否有委托规则
                try {
                    String userId = getUserId(runId, jingbanArray[j]);
                    if (userId != null && userId != "") {
                        jingbanArray[j] = userId;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                fl.setUserId(jingbanArray[j]);
                fl.setCreateTime(DateFormat.getStrDate(new Date()));
                fl.setPrcsTime("0000-00-00 00:00:00");
                fl.setDeliverTime("0000-00-00 00:00:00");
                fl.setActiveTime("0000-00-00 00:00:00");
                fl.setParent(currentPrcsId);
                fl.setParentPrcsId(prcsId);
                if (!StringUtils.checkNull(branchCount)) {
                    fl.setBranchCount(branchCount);
                    //并发多个步骤
                }
                //fl.setBranchCount(branchCount);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("prcsId", fl.getPrcsId());
                map.put("runId", Integer.parseInt(runId));
                map.put("flowPrcs", fl.getFlowPrcs());
                map.put("userId", fl.getUserId());
                List<FlowRunPrcs> list = wfeFlowRunPrcs.selectFind(map);
                //强制合并
                if ("1".equals(flowProcess.getGatherNode())) {
                    Map map1 = new HashMap();
                    map1.put("runId", runId);
                    map1.put("prcsId", prcsId);
                    //查询该步骤是否是并发步骤
                    List<FlowRunPrcs> flowRunPrcsList = wfeFlowRunPrcs.findByRunId1(map1);
                    if (flowRunPrcsList.size() > 0) {
                        //规避设置允许并发，但没有走并发分支
                        if (!StringUtils.checkNull(flowRunPrcsList.get(0).getBranchCount())) {
                            List listPrcs = new ArrayList(); //存储强制合并节点的步骤号
                            //求出能到强制合并节点的步骤号
                            Map ma = new HashMap();
                            ma.put("flowId", flowProcess.getFlowId());
                            ma.put("prcsTo", flowProcess.getPrcsId());
                            String prcsIdStr = wfeFlowProcess.findFlowIdPrcsId(ma);
                            String[] prcsIdArray = null;
                            if (!StringUtils.checkNull(prcsIdStr)) {
                                prcsIdArray = prcsIdStr.split(",");
                                for (String s : prcsIdArray) {
                                    if (!s.equals(currentPrcsId)) {//去除本步骤查询
                                        listPrcs.add(s);
                                    }
                                }
                            }
                            //统计flow——run——prcs这些步骤号prcs_flag状态为(1,2) 是否为1条  为一条 则保存
                            Map<String, Object> m = new HashMap<String, Object>();
                            m.put("runId", runId);
                            m.put("listPrcs", listPrcs);
                            List<Integer> listFlag = new ArrayList<Integer>();
                            listFlag.add(1);
                            listFlag.add(2);
                            m.put("listFlag", listFlag);
                            Integer checkBranchCount = wfeFlowRunPrcs.checkBranchCount(m);


                            if (checkBranchCount == null) {
                                m.put("listFlag", new ArrayList());
                                checkBranchCount = wfeFlowRunPrcs.checkBranchCount(m);
                                if (checkBranchCount == null) {
                                    if (list == null || list.size() == 0) {
                                        fl.setPrcsFlag("6");
                                        fl.setOpFlag("0");
                                        wfeFlowRunPrcs.save(fl);
                                    }
                                } else {
                                    if (list == null || list.size() == 0) {
                                        wfeFlowRunPrcs.save(fl);
                                    } else {
                                        map.put("prcsFlag", 1);
                                        map.put("opFlag", 1);
                                        wfeFlowRunPrcs.updateSql(map);
                                    }
                                }

                            } else {
                                if (list == null || list.size() == 0) {
                                    fl.setPrcsFlag("6");
                                    fl.setOpFlag("0");
                                    wfeFlowRunPrcs.save(fl);
                                }
                            }
                        } else {//否则满足走单条分支，设置允许并发与强制合并
                            wfeFlowRunPrcs.save(fl);
                        }
                    }
                } else {
                    list = wfeFlowRunPrcs.selectFind(map);
                    if (list == null || list.size() == 0) {
                        wfeFlowRunPrcs.save(fl);
                    }
                }

                /*
                //执行发送微信推送消息的方法
                weixinPublicService.saveWorkWeChatNotice(jingbanArray[j], weChatTriggerPlugIn, flowStep, fl);*/
            }
            /** lr               添加转发日志信息         **/
            FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
            flowRunLog.setType(Constant.TYPE1);
            flowRunLog.setRunId(fl.getRunId());
            flowRunLog.setFlowId(fl.getFlowId());
            flowRunLog.setPrcsId(Integer.parseInt(prcsId));
            flowRunLog.setFlowPrcs(Integer.parseInt(currentPrcsId));
            flowRunLog.setGoProcsId(fl.getFlowPrcs() + "");
            flowRunLog.setTransactor(usersService.getUserNameById(alljingbanArray[i]));
            wfeLog.addFlowRunLog(flowRunLog);

            /**                  添加完毕                **/
        }
        try {
            workFlowPlugin.plugin(1);
            toJson.setMsg("OK");
            toJson.setFlag(0);
        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/7/12 13:44
     * 方法介绍:   触发器类型判断
     * CREATE 新建操作  key: 1
     * RECEIVE 接收操作 key: 2
     * SAVE 保存操作   key: 3
     * TURN 转交操作   key: 4
     * INTRUST 委托操作  key: 5
     * BACK 退回操作    key: 6
     * 参数说明:
     *
     * @return
     */
    public Map<Integer, String> returnMap() {
        Map<Integer, String> maps = new HashMap<Integer, String>();
        maps.put(1, "CREATE");
        maps.put(2, "RECEIVE");
        maps.put(3, "SAVE");
        maps.put(4, "TURN");
        maps.put(5, "INTRUST");
        maps.put(6, "BACK");
        return maps;
    }

    //转入和转出条件判断和表单设置
    public FlowFast conditionSetting(int flowId, String flowPrcs) {
        FlowFast flowFast = new FlowFast();
        //获取工作流表单的样式
        //表单类型
        FlowTypeModel flowTypeModel = (FlowTypeModel) wfeFlowType.selectAllFlow(flowId).getObject();
        /*if (!StringUtils.checkNull(flowTypeModel.getViewUserName())) {//   2020/3/19  判断传阅人最后是不是，
            if (!",".equals(flowTypeModel.getViewUserName().substring(flowTypeModel.getViewUserName().length() - 1, flowTypeModel.getViewUserName().length()))) {
                flowTypeModel.setViewUserName(flowTypeModel.getViewUserName() + ",");
            }
        }
        if (!StringUtils.checkNull(flowTypeModel.getViewRoleName())) {//   2020/3/19  判断传阅角色最后是不是，
            if (!",".equals(flowTypeModel.getViewRoleName().substring(flowTypeModel.getViewRoleName().length() - 1, flowTypeModel.getViewRoleName().length()))) {
                flowTypeModel.setViewRoleName(flowTypeModel.getViewRoleName() + ",");
            }
        }
        if (!StringUtils.checkNull(flowTypeModel.getViewDeptName())) {//   2020/3/19  判断传阅部门最后是不是，
            if (!",".equals(flowTypeModel.getViewDeptName().substring(flowTypeModel.getViewDeptName().length() - 1, flowTypeModel.getViewDeptName().length()))) {
                flowTypeModel.setViewDeptName(flowTypeModel.getViewDeptName() + ",");
            }
        }*/

        //表单样式
        FlowFormType flowFormType = wfeFormTypeMapper.qureyItemMax(flowTypeModel.getFormId());
        flowFast.setFlowTypeModel(flowTypeModel);
        flowFast.setFlowFormType(flowFormType);
        //获取所有的流程步骤
        List<FlowProcess> allFp = wfeFlowProcess.findFlowId(flowId);

        for (int i = 0; i < allFp.size(); i++) {
            FlowProcess flowProcess = allFp.get(i);
            if (flowProcess.getPrcsType() == 1) {
                Integer sonFlow = flowProcess.getChildFlow();
                if (sonFlow != null && !sonFlow.equals(0)) {
                    FlowTypeModel flowTypeSon = wfeFlowTypeModelMapper.queryOneObject(sonFlow);
                    if (flowTypeSon != null) {
                        flowProcess.setPrcsName("(子流程)" + flowTypeSon.getFlowName());
                    }
                }
            }
            if (StringUtils.checkNull(flowProcess.getPrcsTo())) {
                if (i == allFp.size() - 1) {
                    flowProcess.setPrcsTo("0");
                }
                flowProcess.setPrcsTo(flowProcess.getPrcsId() + 1 + "");
            }
        }
        flowFast.setListFp(allFp);


        //根据对应条件遍历流程步骤过滤
        Map<String, FlowProcess> map = this.allflowProcessBymap(flowId);
        if (StringUtils.checkNull(flowPrcs) || "0".equals(flowPrcs)) {
            return flowFast;
        }
        FlowProcess flowProcess = map.get(flowPrcs);
        FlowProcess nextfp = null;
        if (!flowProcess.getPrcsTo().contains("0,") && !("").equals(flowProcess.getPrcsTo()) && !(",").equals(flowProcess.getPrcsTo())) {
            String[] a = flowProcess.getPrcsTo().split(",");
            String b = a[0];
            nextfp = map.get(b);
            //转入串
            String prcsIn = (nextfp == null ? "" : nextfp.getPrcsIn());
            //转入逻辑表达式
            String prcsInSet = (nextfp == null ? "" : nextfp.getPrcsInSet());
            flowFast.setPrcsIn(prcsIn);
            flowFast.setPrcsInSet(prcsInSet);
            flowFast.setConditionDesc(flowProcess.getConditionDesc());
        }
        //转出串
        String prcsOut = flowProcess.getPrcsOut();
        //转出逻辑表达式
        String prcsOutSet = flowProcess.getPrcsOutSet();
        flowFast.setPrcsOut(prcsOut);
        flowFast.setPrcsOutSet(prcsOutSet);
        flowFast.setConditionDesc(flowProcess.getConditionDesc());

        flowFast.setPrcsItem(flowProcess.getPrcsItem());
        flowFast.setRequiredItem(flowProcess.getRequiredItem());
        flowFast.setHiddenItem(flowProcess.getHiddenItem());

        String signlock = flowProcess.getSignlook();
        flowFast.setSignlock(signlock);
        //是否允许回退
        String allowBack = flowProcess.getAllowBack();
        flowFast.setAllowBack(allowBack);

        return flowFast;
    }

    //公共附件中的Office文档详细权限设置：(1-新建权限,2-编辑权限,3-删除权限,4-下载权限,5-打印权限,)
    public String attachPriv(FlowProcess flowProcess) {
        String item[] = flowProcess.getPrcsItem().split(",");
        for (String s : item) {
            if (s.equals(Constant.attach)) {
                return flowProcess.getAttachPriv();
            }
        }
        return "";
    }

    //公共附件中的Office文档详细权限设置：(1-新建权限,2-编辑权限,3-删除权限,4-下载权限,5-打印权限,)
    public String workName(FlowProcess flowProcess) {
        String item[] = flowProcess.getPrcsItem().split(",");
        for (String s : item) {
            if (s.equals(Constant.workName)) {
                return "1";
            }
        }
        return "0";
    }

    private FlowRun getRun(String autoName, int flowId, Users users, String beginTime, FlowTypeModel flowTypeModel, Department dep, String runName) {
        FlowRun flowRun = new FlowRun();
        synchronized (this) {
            int runId = wfeFlowRun.getMaxRunId() + 1;
            if (StringUtils.checkNull(runName)) {
                if (StringUtils.checkNull(autoName)) {
                    runName = flowTypeModel.getFlowName() + " " + DateFormat.getStrDate(new Date());
                } else {
                    runName = this.lexicalParse(autoName, flowTypeModel, users, dep, runId);
                }
            } else {
                runName = this.lexicalParse(runName, flowTypeModel, users, dep, runId);
            }

            flowRun = new FlowRun(runId, runName, flowId, users.getUserId(), beginTime, users.getDeptId(), "0");
            // flowRun.setViewUser(viewUser);
            wfeFlowRun.save(flowRun);
            flowRun.setUserName(users.getUserName());
        }
        return flowRun;
    }

    //用map存取所有流程步骤信息
    public Map<String, FlowProcess> allflowProcessBymap(Integer flowId) {
        //获取所有的流程步骤
        List<FlowProcess> allFp = wfeFlowProcess.findFlowId(flowId);
        Map<String, FlowProcess> map = new HashMap<String, FlowProcess>();
        //根据对应条件遍历流程步骤过滤
        for (int i = 0; i < allFp.size(); i++) {
            FlowProcess flowProcess = allFp.get(i);
            map.put(flowProcess.getPrcsId().toString(), flowProcess);
        }
        return map;
    }

    //强制合并判断
    public Integer reGatherNodePriv(String runId, Integer flowPrcs, Integer prcsId, String userId) {
        //找到当前flow_run_prcs
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("prcsId", prcsId - 1);
        map.put("runId", runId);
        //查询上一步流程
        List<FlowRunPrcs> list = wfeFlowRunPrcs.findByRunId1(map);
        //兼容第一步骤无上一步流程
        if (list == null || list.size() <= 0) {
            return 0;
        }
        map.put("flowPrcs", flowPrcs);
        map.put("userId", userId);
        String branchCount = list.get(0).getBranchCount();
        if (!StringUtils.checkNull(branchCount)) {
            String[] processStr = branchCount.split(",");
            List<Integer> listPrcs = new ArrayList<Integer>();
            List<Integer> listFlag = new ArrayList<Integer>();
            listFlag.add(1);
            listFlag.add(2);
            //判断是否已办结
            for (int i = 0; i < processStr.length; i++) {
                if (!StringUtils.checkNull(processStr[i])) {
                    listPrcs.add(Integer.parseInt(processStr[i]));
                }
            }
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("runId", runId);
            m.put("flowPrcs", flowPrcs);
            m.put("listFlag", listFlag);
            m.put("listPrcs", listPrcs);
            Integer gatherNodePriv = wfeFlowRunPrcs.checkGatherNode(m);
            if (gatherNodePriv == null) {
                return 0;
            }
            return 1;
        }
        return 0;
    }


    //强制合并判断
    public Integer reGatherNodePriv(String runId, Integer flowPrcs, String userId, Integer flowId) {
        Map<Integer, FlowProcess> m1 = new HashMap<Integer, FlowProcess>();
        StringBuffer stringBuffer = new StringBuffer();
        List<Integer> listPrcs = new ArrayList<Integer>();
        List<Integer> listFlag = new ArrayList<Integer>();
        //返回所有可以到达此节点的flowProcess
        Map<Integer, FlowProcess> map = this.reAll(m1, flowId, flowPrcs);
        if (map.size() == 0) {
            return 0;
        }

        //通过entrySet()方法将map集合中的映射关系取出（这个关系就是Map.Entry类型）
        Set<Map.Entry<Integer, FlowProcess>> entrySet = map.entrySet();

        //将关系集合entrySet进行迭代，存放到迭代器中
        Iterator<Map.Entry<Integer, FlowProcess>> it2 = entrySet.iterator();

        while (it2.hasNext()) {
            Map.Entry<Integer, FlowProcess> me = it2.next();//获取Map.Entry关系对象me
            Integer key2 = me.getKey();//通过关系对象获取key
            listPrcs.add(key2);
        }
        listFlag.add(1);
        listFlag.add(2);

        Map<String, Object> m = new HashMap<String, Object>();
        m.put("runId", runId);
        m.put("flowPrcs", flowPrcs);
        m.put("listPrcs", listPrcs);
        m.put("listFlag", listFlag);
        m.put("userId", userId);
        Integer gatherNodePriv = wfeFlowRunPrcs.checkGatherNode(m);
        if (gatherNodePriv == null) {
            return 0;
        } else {
            return 1;
        }

    }


    //所有回退步骤
    public List<FlowRunPrcs> reBack(List<FlowRunPrcs> back, FlowRunPrcs flowRunPrcs, String runId) {
        if (!"0".equals(flowRunPrcs.getParent()) && flowRunPrcs != null) {
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("prcsId", flowRunPrcs.getPrcsId() - 1);
            map1.put("flowPrcs", flowRunPrcs.getParent());
            map1.put("runId", runId);
            List<FlowRunPrcs> list = wfeFlowRunPrcs.findByRunId(map1);
            if (list == null || list.size() == 0) {
                map1.put("opFlag", 0);
                list = wfeFlowRunPrcs.selectCondition(map1);
                flowRunPrcs = list.get(0);
                back.add(flowRunPrcs);
            } else {
                flowRunPrcs = list.get(0);
                back.add(flowRunPrcs);
            }
            this.reBack(back, flowRunPrcs, runId);
        }
        return back;
    }


    //遍历获取所有符合的flowProcess
    public Map<Integer, FlowProcess> reAll(Map<Integer, FlowProcess> map, Integer flowId, Integer flowPrcs) {
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("flowId", flowId);
        map1.put("flowPrcs", flowPrcs);
        List<FlowProcess> list = wfeFlowProcess.findProcseePrcsTo(map1);
        for (FlowProcess flowProcess : list) {
            if (flowProcess.getPrcsTo() != null) {
                map.put(flowProcess.getPrcsId(), flowProcess);
                reAll(map, flowId, flowProcess.getPrcsId());
            }
        }
        if (list.size() == 0) {
            return map;
        }
        return map;
    }

    //文号生成规则
    public String lexicalParse(String str, FlowTypeModel flowTypeModel, Users users, Department department, Integer runId) {
        Calendar now = Calendar.getInstance();
        int autoNum = flowTypeModel.getAutoNum();
        int autoLength = flowTypeModel.getAutoLen();

        ++autoNum;
        flowTypeModel.setAutoNum(autoNum);
       /* if (str.contains(DocumentConstants.numberMonth)) {
            flowTypeModel.setAutoNumMonth(flowTypeModel.getAutoNumMonth() == 0 ? 1 : flowTypeModel.getAutoNumMonth() + 1);
        }
        if (str.contains(DocumentConstants.numberYear)) {
            flowTypeModel.setAutoNumYear(flowTypeModel.getAutoNumYear() == 0 ? 1 : flowTypeModel.getAutoNumYear() + 1);
        }*/

        FlowSort flowSort = flowSortMapper.selectByPrimaryKey(flowTypeModel.getFlowSort());
        str = str.replace(DocumentConstants.year, now.get(Calendar.YEAR) + "");
        str = str.replace(DocumentConstants.month, org.apache.commons.lang3.StringUtils.repeat("0", 2 - String.valueOf(now.get(Calendar.MONTH) + 1).length()) + (now.get(Calendar.MONTH) + 1) + "");
        str = str.replace(DocumentConstants.day, org.apache.commons.lang3.StringUtils.repeat("0", 2 - String.valueOf(now.get(Calendar.DAY_OF_MONTH)).length()) + now.get(Calendar.DAY_OF_MONTH) + "");
        str = str.replace(DocumentConstants.hour, now.get(Calendar.HOUR_OF_DAY) + "");
        String minute = null;
        if (now.get(Calendar.MINUTE) >= 10) {
            minute = now.get(Calendar.MINUTE) + "";
        } else {
            minute = "0" + now.get(Calendar.MINUTE);
        }
        str = str.replace(DocumentConstants.minute, minute);
        str = str.replace(DocumentConstants.second, now.get(Calendar.SECOND) + "");
        str = str.replace(DocumentConstants.flow, flowTypeModel.getFlowName());
        str = str.replace(DocumentConstants.user, users.getUserName());
        str = str.replace(DocumentConstants.role, users.getUserPrivName());
        str = str.replace(DocumentConstants.flowName, flowSort.getSortName());
        str = str.replace(DocumentConstants.shortDept, department.getDeptName());
        str = str.replace(DocumentConstants.longDept, departmentService.longDepName(department.getDeptId()));
        str = str.replace(DocumentConstants.number, org.apache.commons.lang3.StringUtils.repeat("0", autoLength - String.valueOf(autoNum).length()) + autoNum);
        if (runId != null) {
            str = str.replace(DocumentConstants.runId, runId.toString());
        }


        String autoNumTime = flowTypeModel.getAutoNumTime();
        String nowTime = DateFormat.getStrDate(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        if (str.contains(DocumentConstants.numberYear)) {
            if (StringUtils.checkNull(autoNumTime)) {
                flowTypeModel.setAutoNumYear(1);
                flowTypeModel.setAutoNumTime(nowTime);
            } else {
                Date date = DateFormat.getDate(autoNumTime);
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(Calendar.YEAR, 1); //把日期往后增加一年，整数往后推，负数往前移
                date = calendar.getTime();
                autoNumTime = sdf.format(date);
                if (StringUtils.checkNull(autoNumTime) || nowTime.compareTo(autoNumTime) > 0) {
                    flowTypeModel.setAutoNumYear(1);
                    flowTypeModel.setAutoNumTime(nowTime);
                } else {
                    flowTypeModel.setAutoNumYear(flowTypeModel.getAutoNumYear() == 0 ? 1 : flowTypeModel.getAutoNumYear() + 1);
                }
            }
        }
        if (str.contains(DocumentConstants.numberMonth)) {
            if (StringUtils.checkNull(autoNumTime)) {
                flowTypeModel.setAutoNumYear(1);
                flowTypeModel.setAutoNumTime(nowTime);
            } else {
                Date date = DateFormat.getDate(autoNumTime);
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(Calendar.MONTH, 1); //把日期往后增加一月
                date = calendar.getTime();
                autoNumTime = sdf.format(date);
                if (StringUtils.checkNull(autoNumTime) || nowTime.compareTo(autoNumTime) > 0) {
                    flowTypeModel.setAutoNumYear(1);
                    flowTypeModel.setAutoNumTime(nowTime);
                } else {
                    flowTypeModel.setAutoNumMonth(flowTypeModel.getAutoNumMonth() == 0 ? 1 : flowTypeModel.getAutoNumMonth() + 1);
                }
            }

        }
        str = str.replace(DocumentConstants.numberYear, org.apache.commons.lang3.StringUtils.repeat("0", autoLength - flowTypeModel.getAutoNumYear().toString().length()) + flowTypeModel.getAutoNumYear());
        str = str.replace(DocumentConstants.numberMonth, org.apache.commons.lang3.StringUtils.repeat("0", autoLength - flowTypeModel.getAutoNumMonth().toString().length()) + flowTypeModel.getAutoNumMonth());
        wfeFlowTypeModelMapper.update(flowTypeModel);
        return str;
    }


    //判断是否有传阅权限
    public String checkViewPriv(int ftViewPriv, int fpViewPriv) {
        if (ftViewPriv == 1 && fpViewPriv == 1) {
            return "1";
        }
        return "0";
    }


    /**
     * 创建作者:   张勇
     * 创建日期:   2017/6/22 16:26
     * 方法介绍:
     * 参数说明:   formmat 公告通知格式(0-普通格式,1-MHT格式,2-超链接),默认为0
     * 参数说明:   userId 按人员发布（公告）
     * 参数说明:   fromId 发送人
     * 参数说明:   sendTime 发送时间（目前只适用于公告，邮件等为时间戳的需要转换）
     * 参数说明:   subject 标题
     * 参数说明:  count 内容
     * 参数说明:  toId2 收件人
     * 参数说明:  flowId 流程Id
     * 参数说明:  flowPrcs 步骤Id
     *
     * @return
     */
    public ToJson notifyNotice(TriggerPlugIn triggerPlugIn) {
        ToJson toJson = new ToJson(1, "error");
        try {
            List<FlowTiggerModel> list = flowTiggerMapper.selectFlowTigger(Integer.parseInt(triggerPlugIn.getFlowId()), Integer.parseInt(triggerPlugIn.getCurrentPrcsId()));
            if (list != null && list.size() > 0) {
                for (int i = 0, len = list.size(); i < len; i++) {
                    if (triggerPlugIn.getFlag().equals(list.get(i).getPluginType()) && 1 == list.get(i).getActived()) {
                        if (list.get(i).getPlugin() != 0 && list.get(i).getBusinessLogicId() != 0) {//判断插件和业务引擎接口都在
                            triggerPlugIn.setDistinguish("1");
                            FlowPluginModel flowPluginModel = flowPluginMapper.selectList(list.get(i).getPlugin());
                            FlowHookWithBLOBs flowHook = new FlowHookWithBLOBs();
                            flowHook.setHid(list.get(i).getBusinessLogicId());
                            FlowHookWithBLOBs flowHook1 = flowHookMapper.selectByhid(flowHook);
                            if (flowHook1 != null) {
                                triggerPlugIn.setHookId(flowHook1.getHid());
                                if (document.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("DocumentTrigger");
                                } else if (attend_leave.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("AttendLeaveTrigger");
                                } else if (attend_evection.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("AttendEvectionTrigger");
                                } else if (attend_out.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("AttendOutTrigger");
                                } else if (budgeting_process.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("BudgetingProcessTrigger");
                                } else if (edu_fixassets.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("EduFixAssetsTrigger");
                                } else if (addNotify.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("NotifyTrigger");
                                    Notify notify = new Notify();
                                    notify.setOpinUsers("");
                                    notify.setOpinionFields("");
                                    notifyMapper.addNotify(notify);
                                    triggerPlugIn.setNotifyId(notify.getNotifyId());
                                } else if (fileContent.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("SaveFileContent");
                                    triggerPlugIn.setSync(true);
                                }
                                Trigger.run("com.xoa.plugin." + flowHook1.getHmodule(), triggerPlugIn.getSqlType(), triggerPlugIn);
                            }

                            inTigger(flowPluginModel.getFlowPluginFlag(), flowPluginModel.getFlowPluginModel(), triggerPlugIn);

                        } else if (list.get(i).getPlugin() != 0) {//判断插件在
                            FlowPluginModel flowPluginModel = flowPluginMapper.selectList(list.get(i).getPlugin());
                            triggerPlugIn.setDistinguish("1");
                            inTigger(flowPluginModel.getFlowPluginFlag(), flowPluginModel.getFlowPluginModel(), triggerPlugIn);
                        } else if (list.get(i).getBusinessLogicId() != 0) {//判断业务引擎接口在
                            FlowHookWithBLOBs flowHook = new FlowHookWithBLOBs();
                            flowHook.setHid(list.get(i).getBusinessLogicId());
                            FlowHookWithBLOBs flowHook1 = flowHookMapper.selectByhid(flowHook);
                            if (flowHook1 != null) {
                                triggerPlugIn.setDistinguish("1");
                                triggerPlugIn.setHookId(flowHook1.getHid());
                                if (document.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("DocumentTrigger");
                                } else if (attend_leave.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("AttendLeaveTrigger");
                                } else if (attend_evection.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("AttendEvectionTrigger");
                                } else if (attend_out.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("AttendOutTrigger");
                                } else if (budgeting_process.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("BudgetingProcessTrigger");
                                } else if (edu_fixassets.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("EduFixAssetsTrigger");
                                } else if (addNotify.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("NotifyTrigger");
                                    Notify notify = new Notify();
                                    notify.setOpinUsers("");
                                    notify.setOpinionFields("");
                                    notifyMapper.addNotify(notify);
                                    triggerPlugIn.setNotifyId(notify.getNotifyId());
                                } else if (fileContent.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("SaveFileContent");
                                    triggerPlugIn.setSync(true);
                                } else if (party_member.equals(flowHook1.getHmodule())) {
                                    flowHook1.setHmodule("PartyMemberTrigger");
                                }
                                Trigger.run("com.xoa.plugin." + flowHook1.getHmodule(), triggerPlugIn.getSqlType(), triggerPlugIn);
                            }
                        }
                    } else {
                        toJson.setFlag(0);
                        toJson.setMsg("ok");
                    }
                }
            } else {
                if (!StringUtils.checkNull(triggerPlugIn.getTableName())) {

                    if ("document".equals(triggerPlugIn.getTableName())) {
                        triggerPlugIn.setDistinguish("1");
                        Trigger.run("com.xoa.plugin.DocumentTrigger", triggerPlugIn.getSqlType(), triggerPlugIn);
                    }


                }


            }
        } catch (Exception e) {
            L.e("workFlowServiceContext.getFlowRunPrcsService()Impl notifyNotice:" + e);
        }
        return toJson;
    }


    //建表,如果没有则新建
    public List<String> createTable(String tableName, String sqlType, List<Map<String, Object>> l) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tableName", tableName);
        if (StringUtils.checkNull(sqlType)) {
            param.put("tableSchema", "xoa1001");
        } else {
            param.put("tableSchema", sqlType);
        }
        //获取该表所有的列
        try {
            //Map<String,Object> list = workMapper.selectColumns(param);
            List<String> columns = workMapper.showColumns(param);
            //没有表则新建
            if (columns.size() == 0) {
                List<String> key = new ArrayList<String>();
                for (Map<String, Object> map : l) {
                    key.add((String) map.get("key"));
                }
                Map<String, Object> param1 = new HashMap();
                param1.put("tableName", tableName);
                param1.put("keys", key);
                //读取配置文件
                ResourceBundle rb = ResourceBundle.getBundle("jdbc-sql");
                String databaseId = rb.getString("driverClassName");
                if (databaseId.contains("oracle")) {
                    workMapper.createSequence(param1);
                }
                workMapper.createTable(param1);
                columns = workMapper.showColumns(param);
            }
            return columns;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 创建作者:   张勇
     * 创建日期:   2017/7/4 12:54
     * 方法介绍:   内部触发器插件工具类
     * 参数说明:
     *
     * @return
     */
    private void inTigger(Integer flag, String flags, TriggerPlugIn tri) {
        ToJson toJson = new ToJson(1, "error");
        // Trigger.run("com.xoa.plugin."+flags,tri);
        switch (flag) {
            case BUILT_IN:
                Trigger.run("com.xoa.plugin." + flags, tri.getSqlType(), tri);
            case BUILT_OUT:
//                                userFilterlist = workFlowServiceContext.getUsersService.getUserByDeptIds(String.valueOf(users.getUserPriv()), 2);
//                                return userFilterlist;

            case BUILT_PUSH:
//                                userFilterlist = workFlowServiceContext.getUsersService.getPUsersByDeptId(users.getDeptId());
//                                return userFilterlist;

            default:


        }

    }

    public Map<String, Object> fastAdd(Integer runId, Integer flowId, HttpServletRequest request) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("tableName", "flow_data_" + flowId);
        maps.put("runId", runId);
        Map<String, Object> m = new HashMap<String, Object>();
        try {
            Object locale = request.getSession().getAttribute("LOCALE_SESSION_ATTRIBUTE_NAME");
            String realPath = request.getSession().getServletContext().getRealPath("/");
            Map<String, String> systemMap = systemInfoService.getSystemInfo(realPath, locale, request);
            String softSerialNo = systemMap.get("softSerialNo");
            m.put("softSerialNo", softSerialNo);
            Map<String, Object> map = workMapper.select(maps);
            Map<String, Object> map2 = new HashMap<String, Object>();
            //针对中电建app手机端办理界面显示效果进行优化
            String userAgent = request.getParameter("userAgent");
            boolean powerIsPc=true;
            String sysPara = sysParaMapper.querySysPara("MYPROJECT").getParaValue();
            if(!StringUtils.checkNull(userAgent)&&userAgent.equals("mobile")&&!StringUtils.checkNull(sysPara) && "powerchina".equals(sysPara)){
                powerIsPc=false;
            }
            //添加父到子映射
            FlowRun flowRun = flowRunMapper.find(runId);
            if (flowRun.getParentRun() != 0) {
                String selectRunId = workMapper.selectData(runId, "flow_data_" + flowId);
                if (selectRunId == null || selectRunId.length() == 0) {
                    //得到父对子映射字段
                    map = ParentSon(flowRun);
                  /*  if(parentSonMap!=null){
                        //得到父流程值
                        List<String> parentDataValue=parentSonMap.get("parentDataValue");
                        //得到子流程字段
                        List<String> sonDataList=parentSonMap.get("sonDataList");
                        if(map==null){
                            map=new HashMap<>();
                        }
                        for(int i=0;i<sonDataList.size();i++){
                            map.put(sonDataList.get(i),parentDataValue.get(i));
                        }
                    }*/
                }
            }

            if (map != null && map.size() != 0) {
                Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry<String, Object> entry = entries.next();
                    if (!("").equals(entry.getValue()) && entry.getValue() != null) {
                        try {
                            String str = (String) entry.getValue();
                            if (str.indexOf("ATTACHMENT_ID") > -1 && str.indexOf("ATTACHMENT_NAME") > -1 && str.indexOf(",") > -1) {
                                // str.replaceAll("\\,", "*");
                                String[] strArray = str.split("&");
                                String string = "";
                                for (int i = 0; i < strArray.length; i++) {
                                    if (strArray[i].indexOf("ATTACHMENT_NAME") == -1) {
                                        strArray[i] = strArray[i].replace(",", "*");
                                        //System.out.print(strArray[i]);
                                    }
                                    if (i == 0) {
                                        string += strArray[i];
                                    } else {
                                        string += "&" + strArray[i];
                                    }
                                }

                                map.put(entry.getKey(), string);
                            }
                            //兼容通达内部附件
                            if (str.indexOf("@") > -1 && str.indexOf("_") > -1 && str.indexOf(",") > -1) {
                                String key = entry.getKey();
                                String sub = key.substring(0, key.lastIndexOf("_"));
                                String attachmentNameStr = map.get(sub).toString();
                                String[] attachmentNames = attachmentNameStr.split("\\*");
                                String[] strArray = str.split(",");
                                StringBuilder stringBuilder = new StringBuilder();
                                if (attachmentNames.length == strArray.length) {
                                    for (int i = 0; i < strArray.length; i++) {
                                        //AID=55474&MODULE=workflow&COMPANY=xoa1000&YM=1901&ATTACHMENT_ID=381668508&ATTACHMENT_NAME=Snipaste_2018-12-26_17-16-03.png&FILESIZE=4.7 KB&userid=admin*
                                        if (strArray[i] != null && strArray[i] != "") {
                                            String str1 = attachmentNames[i];
                                            String str2 = strArray[i];
                                            String aId = str2.substring(0, str2.indexOf("@"));
                                            String ym = str2.substring(str2.indexOf("@") + 1, str2.indexOf("_"));
                                            String attachId = str2.substring(str2.indexOf("_") + 1);
                                            stringBuilder.append("AID=");
                                            stringBuilder.append(aId);
                                            stringBuilder.append("&MODULE=workflow&COMPANY=xoa1000&YM=");
                                            stringBuilder.append(ym);
                                            stringBuilder.append("&ATTACHMENT_ID=");
                                            stringBuilder.append(attachId);
                                            stringBuilder.append("&ATTACHMENT_NAME=");
                                            stringBuilder.append(str1);
//                                            stringBuilder.append("&FILESIZE= KB");
                                            stringBuilder.append("*");
                                        }
                                    }
                                }
                                map.put(sub, stringBuilder);
                            }
                            //电建兼容app效果--将会签意见中空格及换行去掉
                            if (!powerIsPc&&str.contains("class=\"eiderarea\"")&&!entry.getKey().equals("DATA_0")) {//会签控件
                                Document parse = Jsoup.parse(str);
                                Elements select = parse.select("[id=eiderarea]");
                                Iterator<Element> iterator = select.iterator();
                                StringBuffer stringBuffer = new StringBuffer();
                                while (iterator.hasNext()) {
                                    Element element = (Element) iterator.next();
                                    String replace = element.toString().replace("<br>", "");
                                    int i = replace.indexOf("&nbsp;");//出现第一个&nbsp;的位置
                                    String begin = replace.substring(0, i);
                                    String end = replace.substring(i, replace.length());
                                    String substring = begin + "<br>" + end;
                                    stringBuffer.append(substring.replace("&nbsp;", ""));
                                }
                                entry.setValue(stringBuffer.toString());
                            }
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }
                m.put("obj", map);
                m.put("flag", true);
                m.put("msg", "OK");

            } else {
                m.put("flag", true);
                m.put("msg", "NO DATA");
            }
        } catch (Exception e) {
            e.printStackTrace();
            m.put("flag", false);
            m.put("msg", e.getMessage());
        }
        return m;
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月26日 上午9:54:09
     * 方法介绍:   公共附件上传
     * 参数说明:   @param files 上传的文件
     * 参数说明:   @param fmodule 模块名
     * 参数说明:   @param runId  流程实例id
     * 参数说明:   @return
     */
    public ToJson<Attachment> workUpload(MultipartFile[] files, String company, String module, String runId, String flowPrcs, HttpServletRequest request) {
        ToJson<Attachment> json = new ToJson<Attachment>();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            String prcsId = request.getParameter("prcsId");
            List<Attachment> list = enclosureService.upload(files, company, module);

            FlowRunAttach flowRunAttach = new FlowRunAttach();
            Object[] o = FileUploadUtil.reAttachment(list);
            flowRunAttach.setRunId(Integer.valueOf(runId));
            flowRunAttach.setAttachmentId(o[0].toString());
            if (StringUtils.checkNull(flowPrcs)) {
                flowRunAttach.setFlowPrcs(0);
            } else {
                flowRunAttach.setFlowPrcs(Integer.valueOf(flowPrcs));
            }

            Date d = new Date();
            String d1 = DateFormat.getStrDate(d);
            flowRunAttach.setUploadTime(d1);
            flowRunAttach.setUploadUser(users.getUserName());
            flowRunAttach.setAttachmentName(o[1].toString());

            flowRunAttachMapper.insertSelective(flowRunAttach);

            FlowRun flowRun = wfeFlowRun.find(Integer.parseInt(runId));
            String attcahmentId = flowRun.getAttachmentId();
            String attachmentName = flowRun.getAttachmentName();
            StringBuffer id = new StringBuffer();
            StringBuffer name = new StringBuffer();
            if (attcahmentId != "" || attachmentName != "") {
                id.append(attcahmentId);
                name.append(attachmentName);
            }

            map.put("runId", runId);
            if (!StringUtils.checkNull(flowRun.getAttachmentId())) {
                if (!",".equals(flowRun.getAttachmentId().substring(flowRun.getAttachmentId().length() - 1, flowRun.getAttachmentId().length()))) {
                    flowRun.setAttachmentId(flowRun.getAttachmentId() + ",");
                }
            }
            if (!StringUtils.checkNull(flowRun.getAttachmentName())) {
                if (!"*".equals(flowRun.getAttachmentName().substring(flowRun.getAttachmentName().length() - 1, flowRun.getAttachmentName().length()))) {
                    flowRun.setAttachmentName(flowRun.getAttachmentName() + "*");
                }
            }

            map.put("attachmentId", flowRun.getAttachmentId() + o[0].toString());
            map.put("attachmentName", flowRun.getAttachmentName() + o[1].toString());
            wfeFlowRun.updateAttachment(map);
            json.setObj(list);
            json.setMsg("OK");
            json.setFlag(0);
            /****   lr 工作流使用添加日志 --上传附件 ****/
            FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
            FlowProcess process = flowProcessMapper.findProcess(flowRun.getFlowId(), Integer.parseInt(flowPrcs));
            flowRunLog.setPrcsName(process.getPrcsName());
            flowRunLog.setType(Constant.TYPE8);
            flowRunLog.setFlowPrcs(flowRunAttach.getFlowPrcs());
            flowRunLog.setPrcsId(StringUtils.checkNull(prcsId) ? null : Integer.parseInt(prcsId));
            flowRunLog.setRunId(Integer.parseInt(runId));
            flowRunLog.setAccessory(o[1].toString());
            wfeLog.addFlowRunLog(flowRunLog);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;
    }


    //获取表单设置
    public AjaxJson createGuide(String flowId, Users users, HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        try {
            //获取所有的流程步骤
            List<FlowProcess> allFp = wfeFlowProcess.findFlowId(Integer.parseInt(flowId));
            //表单类型
            //本部门
            Department dep = departmentService.getDeptById(users.getDeptId());
            FlowTypeModel flowTypeModel = (FlowTypeModel) wfeFlowType.selectAllFlow(Integer.parseInt(flowId)).getObject();
            FlowFormType flowFormType = wfeFormTypeMapper.qureyItemMax(flowTypeModel.getFormId());
            String flowName = flowTypeModel.getFlowName();
            String autoName = flowTypeModel.getAutoName();
            String beginTime = DateFormat.getStrDate(new Date());
            String runName = this.lexicalParse(autoName, flowTypeModel, users, dep, null);

            if (StringUtils.checkNull(runName.trim())) {
                runName = flowTypeModel.getFlowName() + " " + DateFormat.getStrDate(new Date());
            }

            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("AllFlowProcess", allFp);
            attributes.put("runName", runName);
            attributes.put("flowName", flowName);
            attributes.put("formId", flowFormType.getFormId());
            //流程说明文字
            attributes.put("flowDesc", flowTypeModel.getFlowDesc());
            attributes.put("flowType", flowTypeModel);
            attributes.put("attachmentId", flowTypeModel.getAttachmentId());
            attributes.put("attachmentName", flowTypeModel.getAttachmentName());
            attributes.put("attachList", GetAttachmentListUtil.returnAttachment(flowTypeModel.getAttachmentName(), flowTypeModel.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_WORKFLOW));
            ajaxJson.setAttributes(attributes);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");
            return ajaxJson;
        } catch (Exception e) {
            L.e("createGuide" + e.getMessage());
            ajaxJson.setMsg("fasle");
            ajaxJson.setFlag(false);
            return ajaxJson;
        }
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月28日 上午9:54:09
     * 方法介绍:   查找公共附件
     * 参数说明:   @param runId 流程实例Id
     * 参数说明:   @return
     *
     * @return ToJson<Attachment>
     */
    public ToJson<Attachment> findworkUpload(String runId, String company) {
        ToJson<Attachment> json = new ToJson<Attachment>();
        try {
            List<FlowRunPrcs> flowRunPrcsList = WFEFlowRunPrcsMapper.findMaxFrp(Integer.parseInt(runId));
            Integer prcsId = null;
            if (flowRunPrcsList.size() > 0) {
                prcsId = flowRunPrcsList.get(0).getFlowPrcs();
            }

            //定义用于存储附件信息的集合
            List<Attachment> attachmentList = new ArrayList<Attachment>();
            FlowRun flowRun = wfeFlowRun.findAnnex(Integer.parseInt(runId), prcsId);
            if (flowRun.getAttachmentId() != "" || flowRun.getAttachmentName() != "") {
                String attachmentId[] = flowRun.getAttachmentId().split(",");
                String attachmenName[] = flowRun.getAttachmentName().split("\\*");
                String ATTACH_PRIV = flowRun.getATTACH_PRIV();
                for (int i = 0; i < attachmentId.length; i++) {
                    String aid = attachmentId[i].substring(0, attachmentId[i].indexOf('@'));
                    String ym = attachmentId[i].substring(attachmentId[i].indexOf('@') + 1, attachmentId[i].indexOf('_'));
                    String attachId;
                    String fileSize = "";
                    String time = "";
                    if (attachmentId[i].contains("*")) {
                        attachId = attachmentId[i].substring(attachmentId[i].indexOf('_') + 1, attachmentId[i].indexOf('*'));
                        fileSize = attachmentId[i].substring(attachmentId[i].indexOf('*') + 1, attachmentId[i].indexOf('|'));
                        time = attachmentId[i].substring(attachmentId[i].indexOf('|') + 1, attachmentId[i].length());
                    } else {
                        attachId = attachmentId[i].substring(attachmentId[i].indexOf('_') + 1, attachmentId[i].length());
                    }
                  /*  String attachId = attachmentId[i].substring(attachmentId[i].indexOf('_') + 1, attachmentId[i].indexOf('*'));
                    String fileSize = attachmentId[i].substring(attachmentId[i].indexOf('*') + 1, attachmentId[i].indexOf('|'));
                    String time = attachmentId[i].substring(attachmentId[i].indexOf('|') + 1, attachmentId[i].length());*/


                    Attachment attachment = attachmentMapper.selectByPrimaryKey(Integer.parseInt(aid));
                    if (attachment == null) {
                        attachment = new Attachment();
                        String attachName = attachmenName[i];
                        String attUrl = "AID=" + aid + "&" + "MODULE=" + ModuleEnum.WORKFLOW.getName() + "&" + "COMPANY=" + company + "&" +
                                "YM=" + ym + "&" + "ATTACHMENT_ID=" + attachId + "&" + "ATTACHMENT_NAME=" + attachName;
                        attachment.setAid(Integer.parseInt(aid));
                        attachment.setYm(ym);
                        attachment.setAttachId(attachId);
                        attachment.setAttachName(attachName);
                        attachment.setAttUrl(attUrl);
                        attachment.setFileSize(fileSize);
                        attachment.setTime(time);
                        attachment.setATTACH_PRIV(ATTACH_PRIV);
                        attachmentList.add(attachment);
                    } else {
                        String attUrl = "AID=" + aid + "&" + "MODULE=" + ModuleEnum.WORKFLOW.getName() + "&" + "COMPANY=" + company + "&" +
                                "YM=" + ym + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" + "ATTACHMENT_NAME=" + attachment.getAttachName();
                        attachment.setAttUrl(attUrl);
                        attachment.setFileSize(attachment.getSize());
                        attachment.setTime(time);
                        attachment.setATTACH_PRIV(ATTACH_PRIV);
                        attachmentList.add(attachment);
                    }

                }
            }
            json.setObj(attachmentList);
            json.setFlag(0);
            json.setMsg("OK");

        } catch (Exception e) {
            L.e("findworkUpload" + e);
            json.setFlag(1);
            json.setMsg("false");
        }
        return json;
    }


    /**
     * 创建作者:
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   保存会签意见
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param content 会签内容
     * 参数说明:   @param prcsId  流程实例步骤id
     * 参数说明:   @param flowPrcs  步骤id
     * 参数说明:   @param userId  用户userId
     * 参数说明:   @return
     *
     * @return ToJson<FlowRunPrcs>
     */
    public ToJson<FlowRunFeedback> workfeedback(String content, String runId, String prcsId, String flowPrcs,
                                                String userId, String feedFlag) {
        String editTime = DateFormat.getStrDate(new Date());//设置日期格式
        ToJson<FlowRunFeedback> toJson = new ToJson<FlowRunFeedback>();
        FlowRunFeedback flowRunFeedback = new FlowRunFeedback();
        flowRunFeedback.setContent(content);
        flowRunFeedback.setUserId(userId);
        flowRunFeedback.setPrcsId(Integer.parseInt(prcsId));
        flowRunFeedback.setFlowPrcs(Integer.parseInt(flowPrcs));
        flowRunFeedback.setRunId(Integer.parseInt(runId));
        flowRunFeedback.setEditTime(editTime);
        flowRunFeedback.setFeedFlag(feedFlag);
        //flowRunFeedback.setAttachmentId(attachmentId.toString());
        //flowRunFeedback.setAttachmentName(attachmentName.toString());
        try {
            flowRunFeedbackMapper.insertSelective(flowRunFeedback);
            toJson.setObject(flowRunFeedback);
            toJson.setFlag(0);
            toJson.setMsg("OK");
        } catch (Exception e) {
            toJson.setMsg("false");
            toJson.setFlag(1);
            L.e("workfeedback" + e);
        }
        return toJson;
    }

    /**
     * 增加会签人会签设置，并向会签人发起事务提醒
     * 王禹萌
     * 2018-08-07 15：01
     *
     * @param runId
     * @param prcsId
     * @param flowPrcs
     * @param userId
     * @param flowId
     * @param runName
     * @return
     */
    public ToJson<SmsBody> addFeedback(HttpServletRequest request, Integer runId, Integer prcsId, String flowPrcs, String userId, Integer flowId, String runName, String topFlag) {
        //当前登陆人
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        ToJson<SmsBody> toJson = new ToJson<SmsBody>();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        FlowRunPrcs flowRunPrcs1 = wfeFlowRunPrcs.selectFind(prcsId, runId, Integer.parseInt(flowPrcs), users.getUserId(), null).get(0);
        DocumentModel documentModel = documentSerivce.checkRunId(runId);
        try {
            boolean bol = false;
            SysPara myproject = sysParaMapper.querySysPara("MYPROJECT");
            if (myproject != null && !StringUtils.checkNull(myproject.getParaValue())
                    && "dazu".equals(myproject.getParaValue())) {
                bol = true;
            }
            //对加签人进行拆分
            String[] userIdStr = userId.split(",");
            for (int i = 0; i < userIdStr.length; i++) {
                List<FlowRunPrcs> frps = wfeFlowRunPrcs.selectFind(prcsId, runId, Integer.parseInt(flowPrcs), userIdStr[i], null);
                if (frps.size() == 0) {//判断是否加签过，加签过则只更改状态值
                    //该流程操作插入flow_run_prcs中
                    FlowRunPrcs flowRunPrcs = new FlowRunPrcs();
                    flowRunPrcs.setOpaddUser(users.getUserId());
                    flowRunPrcs.setRunId(runId);
                    flowRunPrcs.setPrcsId(prcsId);
                    flowRunPrcs.setUserId(userIdStr[i]);
                    //工作接收时间
                    flowRunPrcs.setPrcsTime(time);
                    flowRunPrcs.setDeliverTime("0000-00-00 00:00:00");
                    //设置步骤状态为未接受
                    flowRunPrcs.setPrcsFlag("1");
                    flowRunPrcs.setFlowPrcs(Integer.valueOf(flowPrcs));
                    //是否主办人(增加会签人加签只给经办人加签)
                    flowRunPrcs.setOpFlag("0");
                    flowRunPrcs.setTopFlag(topFlag);
                    //上一流程ID是flow_prcs  -1
                    flowRunPrcs.setParent(flowRunPrcs1.getParent());
                    flowRunPrcs.setChildRun(0);
                    flowRunPrcs.setTimeOut("");
                    flowRunPrcs.setTimeOutType(0);
                    flowRunPrcs.setTimeOutFlag("0");
                    flowRunPrcs.setCreateTime(time);
                    flowRunPrcs.setFromUser("");
                    flowRunPrcs.setActiveTime("0000-00-00 00:00:00");
                    flowRunPrcs.setPrcsDept(0);
                    flowRunPrcs.setParentPrcsId(flowRunPrcs1.getParentPrcsId());
                    flowRunPrcs.setBackPrcsId(0);
                    flowRunPrcs.setBackFlowPrcs(0);
                    flowRunPrcs.setTimeOutAttend(0);
                    flowRunPrcs.setTimeOutTemp("0");
                    flowRunPrcs.setRunPrcsName("");
                    flowRunPrcs.setRunPrcsId("");
                    flowRunPrcs.setMobileFlag(0);
                    flowRunPrcs.setIsRemind(0);
                    flowRunPrcs.setTempPrcsFlag(0);
                    flowRunPrcs.setWorkingdaysType("0");
                    flowRunPrcs.setFreeItem("");
                    flowRunPrcs.setOtherUser("");
                    int count = flowRunPrcsMapper.insert(flowRunPrcs);
                } else {
                    FlowRunPrcs frp = frps.get(0);
                    frp.setOpaddUser(users.getUserId());
                    frp.setDeliverTime("0000-00-00 00:00:00");
                    frp.setPrcsTime("0000-00-00 00:00:00");
                    frp.setPrcsFlag("1");
                    wfeFlowRunPrcs.updateFrpById(frp);
                }
                //为加签人设置事务提醒
                final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
                String title = "";
                String context = "";
                String remindUrl = "";
                SmsBody smsBody = null;
                if (documentModel != null) {
                    title = bol ? runName : "您有新的公文需要签阅";
                    context = "流水号：" + runId + "，公文文号：" + runName;
                    remindUrl = "/workflow/work/workform?opflag=0&flowId=" + flowId + "&flowStep=" + prcsId + "&tableName=document&tabId=" + documentModel.getId() + "&runId=" + runId + "&prcsId=" + flowPrcs + "&isNomalType=false";
                    smsBody = new SmsBody(users.getUserId(), "70", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, context);
                    smsBody.setToId(userIdStr[i]);
                } else {
                    title = bol ? runName : "您有新的工作需要办理";
                    remindUrl = "/workflow/work/workform?opflag=0&flowId=" + flowId + "&flowStep=" + prcsId + "&runId=" + runId + "&prcsId=" + flowPrcs;
                    context = "流水号：" + runId + "，工作名称/文号：" + runName;
                    smsBody = new SmsBody(users.getUserId(), "7", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, context);
                    smsBody.setToId(userIdStr[i]);
                }
                toJson = smsService.saveSms(smsBody, userIdStr[i], "1", "1", title, context, sqlType);//存储事物提醒并推送消息
                toJson.setObject(smsBody);
                toJson.setFlag(0);
                toJson.setMsg("OK");
            }
/**         lr 工作流使用添加日志 ----增加会签人会签**/
            FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
            //装配日志对象
            flowRunLog.setUserId(users.getUserId());
            flowRunLog.setType(Constant.TYPE20);
            flowRunLog.setTransactor(usersService.getUserNameById(userId));
            flowRunLog.setRunId(runId);
            flowRunLog.setFlowPrcs(flowRunPrcs1.getFlowPrcs());
            flowRunLog.setPrcsId(prcsId);
            //添加日志
            wfeLog.addFlowRunLog(flowRunLog);
        } catch (Exception e) {
            toJson.setMsg("false");
            toJson.setFlag(1);
        }
        return toJson;
    }


    /**
     * 获取加签人为经办人
     * 王禹萌
     * 2018-08-10 11：15
     *
     * @param runId
     * @param prcsId
     * @param flowPrcs
     * @return
     */
    public BaseWrappers getFlowRunPrecsUser(String runId, Integer prcsId, Integer flowPrcs) {
        BaseWrappers wrappers = new BaseWrappers();
        Map map = new HashMap();
        map.put("runId", runId);
        map.put("prcsId", prcsId);
        map.put("flowPrcs", flowPrcs);
        try {
            List<FlowRunPrcs> flowRunPrcsList = flowRunPrcsMapper.getFlowRunPrecsUser(map);
            wrappers.setFlag(true);
            wrappers.setStatus(true);
            wrappers.setObject(flowRunPrcsList);
        } catch (Exception e) {
            wrappers.setFlag(false);
            wrappers.setMsg("失败");
            e.printStackTrace();
        }
        return wrappers;
    }


    /**
     * 创建作者:
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   查找会签意见
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param content 会签内容
     * 参数说明:   @param prcsId  流程实例步骤id
     * 参数说明:   @param flowPrcs  步骤id
     * 参数说明:   @param feedback  会签
     * 参数说明:   @return
     *
     * @return ToJson<FlowRunFeedback>
     */
    public AjaxJson findworkfeedback(String runId, String prcsId, String flowPrcs, String userId, String company, String signlock) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("prcsId", Integer.parseInt(prcsId));
            map.put("runId", Integer.parseInt(runId));
            map.put("flowPrcs", flowPrcs);
            map.put("userId", userId);
            FlowTypeModel flowTypeModel = wfeFlowType.sfTbyrunId(Integer.parseInt(runId));
            String flowType = flowTypeModel.getFlowType();
            Integer flowId = flowTypeModel.getFlowId();
            //获取所有流程步骤
            List<FlowRunFeedback> modelList = this.selectFlowFeedBackByRunId(runId);
            //固定流程
            if (("1").equals(flowType)) {
                //获取该流程所有步骤
                List<FlowProcess> allFp = wfeFlowProcess.findFlowId(flowId);
                for (FlowProcess flowProcess : allFp) {
                    //处理不是当前节点的会签可见性
                    if (!String.valueOf(flowProcess.getPrcsId()).equals(flowPrcs)) {
                        //针对其他步骤不可见
                        if (("2").equals(flowProcess.getSignlook())) {
                            Iterator<FlowRunFeedback> it = modelList.iterator();
                            while (it != null && it.hasNext()) {
                                FlowRunFeedback fbm = it.next();
                                if (fbm.getFlowPrcs() == flowProcess.getPrcsId()) {
                                    it.remove();
                                }
                            }
                        }
                    } else {//处理是当前节点的会签可见性
                        if (("1").equals(flowProcess.getSignlook())) {//本步骤经办人之间不可见
                            Iterator<FlowRunFeedback> it = modelList.iterator();
                            while (it != null && it.hasNext()) {
                                FlowRunFeedback fbm = it.next();
                                if (fbm.getFlowPrcs() == flowProcess.getPrcsId() && !userId.equals(fbm.getUserId())) {
                                    it.remove();
                                }
                            }
                        }
                    }
                }
            }
            for (FlowRunFeedback flowRunFeedback : modelList) {
                Users users = usersService.findUsersByuserId(flowRunFeedback.getUserId());
                String editTime = flowRunFeedback.getEditTime().substring(0, flowRunFeedback.getEditTime().length() - 2);
                flowRunFeedback.setEditTime(editTime);
                flowRunFeedback.setUsers(users);
            }
            for (FlowRunFeedback flowRunFeedback : modelList) {
                String u = flowRunFeedback.getUserId();
                Users users = usersService.getUsersByuserId(u);
              /*  if (users.getAvatar().equals("0")){
                    users.setAvatar("../../img/user/girl.jpg");
                }
                if (users.getAvatar().equals("1")){
                    users.setAvatar("../../img/user/boy.jpg");
                }*/
                flowRunFeedback.setUsers(users);
            }
            ajaxJson.setObj(modelList);
            ajaxJson.setMsg("OK");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg("false");
        }
        return ajaxJson;
    }


    public List<FlowRunFeedback> selectFlowFeedBackByRunId(String runId) {
        FlowTypeModel flowTypeModel = wfeFlowType.sfTbyrunId(Integer.parseInt(runId));
        String flowType = flowTypeModel.getFlowType();
        Integer flowId = flowTypeModel.getFlowId();
        List<FlowRunFeedback> list = new ArrayList<FlowRunFeedback>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("runId", Integer.parseInt(runId));
        //如果是自由流程
        if (("2").equals(flowType)) {
            list = flowRunFeedbackMapper.selectRunId(map);
        } else {
            list = flowRunFeedbackMapper.selectFeedBackByRunId(map);
        }
        return list;
    }


    /**
     * @param flowId          流程实例步骤id
     * @param runId           流程实例Id
     * @param flowPrcs        步骤id
     * @param currentFlowPrcs 当前步骤id
     * @param users           用户
     * @param search          搜索
     * @return
     * @author zlf
     */
    public AjaxJson findBranch(String flowId, String runId, String flowPrcs, String currentFlowPrcs, Users users, String search, String deptNo) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, FlowFast> mAll = new HashMap<String, FlowFast>();
        try {
            String[] fpArray = flowPrcs.split(",");
            for (int j = 0; j < fpArray.length; j++) {
                if (!("0").equals(fpArray[j])) {
                    //获取当前流程
                    FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(Integer.parseInt(flowId), Integer.parseInt(fpArray[j]));

                    FlowFast flowFast = new FlowFast();
                    flowFast.setFlowProcesses(flowProcess);
                    //本部门
                    Department dep = departmentService.getDeptById(users.getDeptId());

                    Map<String, Object> mC = new HashMap<String, Object>();
                    mC.put("runId", runId);
                    List<FlowRunPrcs> allFrp = wfeFlowRunPrcs.findByRunId(mC);
                    //获取所有经办人
                    Map<String, Object> mapUser = new HashMap<String, Object>();
                    mapUser.put("flowId", flowProcess.getFlowId());
                    mapUser.put("prcsId", flowProcess.getPrcsId());
                    mapUser.put("prcsPriv", flowProcess.getPrcsPriv() == "" ? null : flowProcess.getPrcsPriv().split(","));
                    mapUser.put("prcsDept", flowProcess.getPrcsDept() == "" ? null : flowProcess.getPrcsDept().split(","));

                    List<Users> privListByProcess = null;
                    //判断该参数中设置的是本分级机构人员范围
                    // SysPara sysPara = sysParaMapper.querySysPara("ORG_SCOPE");
                    if (!StringUtils.checkNull(deptNo)) {
                        //如果范围是分级机构
                        String[] deptNoStr = deptNo.split(",");
                        mapUser.put("deptNo", deptNoStr);
                    }
                    //获取所有符合要求的用户
                    List<Users> allUser = usersService.getAllUser(mapUser);
                    //获取所有符合要求用户的角色
                    //privListByProcess = usersService.getAllPrivByProcess(mapUser);
                    //flowFast.setPrcsPrivlist(privListByProcess);
                 /*   Map<String, List<Users>> allprcsUserlist = new LinkedHashMap<String, List<Users>>();
                    for (int i = 0, size = privListByProcess.size(); i < size; i++) {
                        Integer userPriv = privListByProcess.get(i).getUserPriv();
                        String userPrivName = privListByProcess.get(i).getUserPrivName();
                        mapUser.put("userPriv", userPriv);
                        List<Users> userListByProcessPriv = usersService.getUserByProcessPriv(mapUser);
                        allprcsUserlist.put(userPrivName, userListByProcessPriv);
                    }
                    flowFast.setAllprcsUserlist(allprcsUserlist);*/

                    //  List<Users> allUser =new ArrayList<Users>();
                    //-----------------------------------wym 将辅助角色辅助部门填入经办人集合中
              /*      FlowProcess fp = wfeFlowProcessMapper.findProcess(flowProcess.getFlowId(), flowProcess.getPrcsId());
                    String prcsPriv = fp.getPrcsPriv();
                    if (!"".equals(prcsPriv)) {
                        String[] prcsPrivStr = prcsPriv.split(",");
                        for (int i = 0; i < prcsPrivStr.length; i++) {
                            List<Users> users1 = usersMapper.queryUserprivOhter(prcsPrivStr[i]);
                            for (Users uu : users1) {
                                allUser.add(uu);
                            }
                        }
                    }
                    String deptStr = fp.getPrcsDept();
                    if (!"".equals(deptStr)) {
                        String[] deptDeptStr = deptStr.split(",");
                        for (int i = 0; i < deptDeptStr.length; i++) {
                            List<Users> users1 = usersMapper.queryUserDeptOhter(deptDeptStr[i]);
                            for (Users uu : users1) {
                                allUser.add(uu);
                            }
                        }
                    }
                    //-----------------------------------*/
                    //去重
                    Map<Integer, Users> m = new LinkedHashMap<Integer, Users>();
                    for (Users users1 : allUser) {
                        m.put(users1.getUid(), users1);
                    }
                    //选人过滤规则
                    String uF = flowProcess.getUserFilter();
                    //选人过滤规则
                    List<Users> userFilterlist = new ArrayList<Users>();
                    //选人过滤规则判断
                    if (flowProcess.getUserFilter().trim() != "" && !"0".equals(flowProcess.getUserFilter().trim())) {
                        Integer userFilter = Integer.parseInt(flowProcess.getUserFilter());
                        //允许选择的经办人
                        userFilterlist = this.userFilterlist(userFilter, users, flowProcess);
                        if (userFilterlist != null && userFilterlist.size() > 0) {
                            Map<Integer, Users> m1 = new LinkedHashMap<Integer, Users>();
                            for (Users users1 : userFilterlist) {
                                m1.put(users1.getUid(), users1);
                            }
                            userFilterlist = new ArrayList<Users>(m1.values());
                            allUser = new ArrayList<Users>();
                            for (Users u : userFilterlist) {
                                if (m.containsKey(u.getUid())) {
                                    allUser.add(u);
                                }
                            }
                        }
                    }

                   /* Collections.sort(allUser, new Comparator<Users>() {
                        @Override
                        public int compare(Users o1, Users o2) {
                            int i = o1.getUserPrivNo() - o2.getUserPrivNo();
                            if(i == 0){
                                return o1.getUserNo() - o2.getUserNo();
                            }
                            return i;
                        }
                    });*/

                    flowFast.setUserFilter(uF);
                    flowFast.setPrcsUserlist(allUser);
                    //存储所有经办人map（用于遍历移除）
                    Map<Integer, Object> map1 = new LinkedHashMap<Integer, Object>();
                    for (Users u : allUser) {
                        map1.put(u.getUid(), u);
                    }
                    //搜索处理
                    allUser = this.reSearch(allUser, search);
                    //自动选人规则
                    String aT = flowProcess.getAutoType();
                    List<Users> autoTypelist = null;
                    if (aT != "") {
                        Integer autoType = Integer.parseInt(aT);
                        try {
                            autoTypelist = this.autoTypelist(autoType, dep, users, runId, flowProcess, allFrp);
                            List<Users> a = new ArrayList<Users>();
                            //判断自动选人是否是经办人
                            if (autoTypelist != null && autoTypelist.size() > 0) {
                                //是否设置了经办权限，如未设置，智能选人范围为全体人员，若有经办权限，智能选人范围在经办权限内
                                if (StringUtils.checkNull(flowProcess.getPrcsUser()) && StringUtils.checkNull(flowProcess.getPrcsDept()) && StringUtils.checkNull(flowProcess.getPrcsPriv())) {
                                    for (Users users1 : autoTypelist) {
                                        a.add(users1);
                                    }
                                    flowFast.setPrcsUserlist(a);
                                } else {
                                    for (Users users1 : autoTypelist) {
                                        if (map1.containsKey(users1.getUid())) {
                                            a.add(users1);
                                        }
                                    }
                                }

                            }
                            flowFast.setAutoType(aT);
                            flowFast.setAutoTypelist(a);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (allUser.size() == 1) {
                        autoTypelist = allUser;
                        Users users1 = autoTypelist.get(0);
                        users1.setOpFlag("1");
                        flowFast.setAutoTypelist(autoTypelist);
                    }
                    mAll.put(fpArray[j], flowFast);
                }
            }
            ajaxJson.setObj(mAll);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");
        } catch (Exception e) {
            L.e("findBranch" + e);
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            return ajaxJson;
        }
        return ajaxJson;
    }


    /**
     * 工作流选人获取所有可选人员
     *
     * @param flowId     流程编号
     * @param flowPrcs   步骤号
     * @param deptId     部门id（用以接收按部门选人参数）
     * @param userPriv   角色编号（用以接收按角色选人参数）
     * @param pageParams 分页插件
     * @return
     */
    public AjaxJson getWorkFlowUser(Integer flowId, Integer flowPrcs, Users user, Integer deptId, Integer userPriv, String deptNo, String search, PageParams pageParams) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Users> temp = new ArrayList<Users>();
        try {
            user = usersMapper.selectUserByUId(user.getUid());
            List<Integer> allUid = this.getWorkFlowUid(flowId, flowPrcs, user, deptNo);
            if (allUid != null && allUid.size() > 0) {
                map.put("allUid", allUid);
                map.put("page", pageParams);
                if (!StringUtils.checkNull(search)) {
                    //【全为英文】返回true  否则false
                    boolean result = search.matches("[a-zA-Z]+");
                    if (result) {
                        char[] chars = search.toCharArray();
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int i = 0; i < chars.length; i++) {
                            stringBuffer.append(chars[i]).append("*");
                        }
                        map.put("search1", stringBuffer.toString());
                    }
                    map.put("search", search);
                }
                if (null != deptId) {
                    map.put("deptId", deptId);
                }
                if (null != userPriv) {
                    map.put("userPriv", userPriv);
                }
                temp = usersService.getWorkFlowUser(map);
            }
            ajaxJson.setObj(temp);
            if (pageParams.getUseFlag()) {
                ajaxJson.setTotleNum(allUid.size());
            }
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
        }
        return ajaxJson;
    }

    //搜索
    public List<Users> reSearch(List<Users> allUser, String search) {
        // 张航宁
        // 判断查询搜索条件
        if (!StringUtils.checkNull(search)) {
            List<Users> searchList = new ArrayList<Users>();
            for (Users users1 : allUser) {
                if (!StringUtils.checkNull(users1.getUserName())) {
                    if (users1.getUserName().indexOf(search) >= 0) {
                        searchList.add(users1);
                    }
                }
                if (!StringUtils.checkNull(users1.getByname())) {
                    if (users1.getByname().indexOf(search) >= 0) {
                        searchList.add(users1);
                    }
                }
                if (!StringUtils.checkNull(users1.getUserNameIndex())) {
                    if (users1.getUserNameIndex().indexOf(search) >= 0) {
                        searchList.add(users1);
                    }
                }
            }
            allUser = searchList;
        }
        return allUser;
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月25日 上午10:31:07
     * 方法介绍:   选人过滤规则判断
     * 参数说明:   @param userFilter 过滤规则
     * 参数说明:   @param users   用户信息
     * 参数说明:   @return
     *
     * @return List<Users>
     */
    public List<Users> userFilterlist(Integer userFilter, Users users, FlowProcess flowProcess) {
        List<Users> userFilterlist = new ArrayList<Users>();
        //当前用户部门
        Department department = departmentService.getDeptById(users.getDeptId());
        Department dparent = null;
        List<Department> list = null;
        switch (userFilter) {
            case 1://只允许本部门
                userFilterlist = usersService.getUserByDeptIds(users.getDeptId().toString(), 5);
                return userFilterlist;
            case 2://只允许本角色
                userFilterlist = usersService.getUserByDeptIds(String.valueOf(users.getUserPriv()), 6);
                return userFilterlist;
            case 3://只允许选择上级部门
                if (department.getDeptParent() == 0) {
                } else {
                    dparent = departmentService.getDeptById(department.getDeptParent());
                    userFilterlist = usersService.getUserByDeptIds(dparent.getDeptId().toString(), 5);
                }
                return userFilterlist;
            case 4://只允许选择下级部门
                list = departmentService.getChDept(users.getDeptId());
                if (list != null && list.size() > 0) {
                    StringBuffer stringBuffer = new StringBuffer();
                    for (Department department1 : list) {
                        stringBuffer.append(department1.getDeptId()).append(",");
                    }
                    userFilterlist = usersService.getUserByDeptIds(stringBuffer.toString(), 5);
                }
                return userFilterlist;
            case 5://同级部门
                if (department.getDeptParent() == 0) {
                    list = departmentService.getDepartmentByParet();
                } else {
                    dparent = departmentService.getDeptById(department.getDeptParent());
                    list = departmentService.getChDept(dparent.getDeptId());
                }
                if (list != null && list.size() > 0) {
                    StringBuffer stringBuffer = new StringBuffer();
                    for (Department department1 : list) {
                        stringBuffer.append(department1.getDeptId()).append(",");
                    }
                    userFilterlist = usersService.getUserByDeptIds(stringBuffer.toString(), 5);
                }
                userFilterlist = usersService.getTUsersByDeptId(users.getDeptId());
                return userFilterlist;
            case 6://指定部门
                userFilterlist = usersService.getUserByDeptIds(flowProcess.getUserFilterPrcsDept(), 5);
                return userFilterlist;
            case 7://指定角色
                userFilterlist = usersService.getUserByDeptIds(flowProcess.getUserFilterPrcsPriv(), 6);
                return userFilterlist;
            case 8://本辅助部门
                userFilterlist = usersService.getUserByDeptIds(users.getDeptIdOther(), 3);
                return userFilterlist;
            case 9://指定辅助部门
                userFilterlist = usersService.getUserByDeptIds(flowProcess.getUserFilterPrcsDeptOther(), 3);
                return userFilterlist;
            case 10://本辅助角色
                userFilterlist = usersService.getUserByDeptIds(users.getUserPrivOther(), 4);
                return userFilterlist;
            case 11://指定辅助角色经办人
                userFilterlist = usersService.getUserByDeptIds(flowProcess.getUserFilterPrcsPrivOther(), 4);
                return userFilterlist;
            case 12://本部门和下级部门
                userFilterlist = usersService.getUserByDeptIds(users.getDeptId().toString(), 5);
                list = departmentService.getChDept(users.getDeptId());
                List<Users> nextDep = new ArrayList<Users>();
                if (list != null && list.size() > 0) {
                    StringBuffer stringBuffer = new StringBuffer();
                    for (Department department1 : list) {
                        stringBuffer.append(department1.getDeptId()).append(",");
                    }
                    nextDep = usersService.getUserByDeptIds(stringBuffer.toString(), 5);
                }
                userFilterlist.addAll(nextDep);
                return userFilterlist;
            default:
                return userFilterlist;
        }
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月25日 上午10:31:07
     * 方法介绍:   自动选人规则
     * 参数说明:   @param autoType 选人
     * 参数说明:   @param users   用户信息
     * 参数说明:   @param dep  部门信息
     * 参数说明:   @return
     *
     * @return List<Users>
     */
    public List<Users> autoTypelist(Integer autoType, Department dep, Users users, String runId, FlowProcess flowProcess, List<FlowRunPrcs> allfrp) {
        List<Users> autoTypelist = new ArrayList<Users>();
        //部门针对对象步骤id
        Integer autoBaseUser = flowProcess.getAutoBaseUser();
        Department department = null;
        Department dparent = null;
        List<Users> list = null;
        switch (autoType) {
            case 1://自动选择流程发起人
                FlowRun flowRun = wfeFlowRun.find(Integer.parseInt(runId));
                Users u = usersService.findUsersByuserId(flowRun.getBeginUser());
                u.setOpFlag("1");
                autoTypelist.add(u);
                return autoTypelist;
            case 2://自动选择本部门主管
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        department = departmentService.getDeptById(users.getDeptId());
                        if (department != null) {
                            if (!StringUtils.checkNull(department.getManager())) {
                                autoTypelist = usersService.getUserByuserId(department.getManager());
                            }
                        }
                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users users1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getDeptById(users1.getDeptId());
                            autoTypelist = usersService.getUserByuserId(department.getManager());
                        }
                    }
                }
                if (autoTypelist.size() == 1) {
                    for (Users users1 : autoTypelist) {
                        users1.setOpFlag("1");
                    }
                }
                return autoTypelist;
            case 3://自动选择默认人员
                //默认主办人
               /* Users usersOp = null;
                if (!StringUtils.checkNull(flowProcess.getAutoUserOp())){
                    usersOp = usersService.findUsersByuserId(flowProcess.getAutoUserOp());
                    usersOp.setOpFlag("1");
                }
*/
                //默认经办人
                List<Users> usersList = usersService.getUserByuserId(flowProcess.getAutoUser());
                Iterator<Users> iterator = usersList.iterator();
                while (iterator.hasNext()) {
                    Users users1 = iterator.next();
                    if (!StringUtils.checkNull(flowProcess.getAutoUserOp())) {
                        if (users1.getUserId().equals(flowProcess.getAutoUserOp())) {
                            users1.setOpFlag("1");
                            break;
                        }
                    } else {
                        users1.setOpFlag("1");
                        break;
                    }
                }
                autoTypelist.addAll(usersList);
                return autoTypelist;
            case 4://自动选择上级主管领导
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        department = departmentService.getDeptById(users.getDeptId());
                        // dparent = departmentService.getDeptById(department.getDeptParent());
                        if (department != null) {
                            if (!StringUtils.checkNull(department.getLeader1())) {
                                autoTypelist = usersService.getUserByuserId(department.getLeader1());
                            }
                        }
                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users users1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getDeptById(users1.getDeptId());
                            // dparent = departmentService.getDeptById(department.getDeptParent());
                            if (department != null) {
                                if (!StringUtils.checkNull(department.getLeader1())) {
                                    autoTypelist = usersService.getUserByuserId(department.getLeader1());
                                }
                            }
                        }
                    }
                }
                if (autoTypelist.size() == 1) {
                    for (Users users1 : autoTypelist) {
                        users1.setOpFlag("1");
                    }
                }
                return autoTypelist;
            case 5://自动选择一级部门主管
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        department = departmentService.getFatherDept(users.getDeptId());
                        if (department != null) {
                            if (!StringUtils.checkNull(department.getManager())) {
                                autoTypelist = usersService.getUserByuserId(department.getManager());
                            }
                        }

                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users users1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getFatherDept(users1.getDeptId());
                            if (department != null) {
                                if (!StringUtils.checkNull(department.getManager())) {
                                    autoTypelist = usersService.getUserByuserId(department.getManager());
                                }
                            }
                        }
                    }
                }
                if (autoTypelist.size() == 1) {
                    for (Users users1 : autoTypelist) {
                        users1.setOpFlag("1");
                    }
                }
                return autoTypelist;
            case 6://自动选择上级分管主管
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        //department = departmentService.getFatherDept(users1.getDeptId());
                        dparent = departmentService.getDeptById(users.getDeptId());
                        if (dparent != null) {
                            autoTypelist = usersService.getUserByuserId(dparent.getLeader2());
                        }
                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users users1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            //department = departmentService.getFatherDept(users1.getDeptId());
                            dparent = departmentService.getDeptById(users1.getDeptId());
                            if (dparent != null) {
                                autoTypelist = usersService.getUserByuserId(dparent.getLeader2());
                            }
                        }
                    }
                }
                if (autoTypelist.size() == 1) {
                    for (Users users1 : autoTypelist) {
                        users1.setOpFlag("1");
                    }
                }
                return autoTypelist;
            case 7://按表单字段选择
                String autoUser = flowProcess.getAutoUser();
                String a[] = autoUser.split(",");
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("tableName", "flow_data_" + flowProcess.getFlowId());
                map.put("runId", runId);
                Map<String, Object> maps = workMapper.select(map);
                Users aUser = null;
                if (maps != null) {
                    String userName = (String) maps.get("DATA_" + a[0]) == null ? (String) maps.get("data_" + a[0]) : (String) maps.get("DATA_" + a[0]);
                    if (StringUtils.checkNull(userName)) {
                        userName = (String) maps.get(a[0].toLowerCase()) == null ? (String) maps.get(a[0].toUpperCase()) : (String) maps.get(a[0].toLowerCase());
                    }
                    if (userName.contains("|")) {
                        String uNames[] = userName.split("\\|");
                        String userIds = uNames[0];
                        autoTypelist = usersService.getUserByuserId(userIds);
                    } else if (userName.contains("_")) {
                        String u1 = userName.substring(userName.indexOf("_") + 1, userName.length());
                        aUser = usersService.getUserByUserName(u1);
                        if (aUser != null) {
                            autoTypelist.add(aUser);
                        }
                    } else {
                        String usName[] = userName.split(",");
                        for (int i = 0; i < usName.length; i++) {
                            aUser = usersService.getUserByUserName(usName[i]);
                            if (aUser != null) {
                                autoTypelist.add(aUser);
                            }
                        }
                    }
                }
                if (autoTypelist != null && autoTypelist.size() > 0) {
                    autoTypelist.get(0).setOpFlag("1");
                }
                return autoTypelist;
            case 8://指定步骤主办人
                //获取指定步骤
                Integer step = flowProcess.getAutoBaseUser();
                String userId = wfeFlowRunPrcs.getUserIdByMaxFlowPrcs(step, Integer.parseInt(runId));
                if (!StringUtils.checkNull(userId)) {
                    Users users1 = usersService.findUsersByuserId(userId);
                    autoTypelist.add(users1);
                    return autoTypelist;
                }
                return autoTypelist;
            case 9://自动选择本部门助理
                autoTypelist = usersService.getUserByuserId(dep.getAssistantId());
                if (autoTypelist.size() == 1) {
                    for (Users users1 : autoTypelist) {
                        users1.setOpFlag("1");
                    }
                }
                return autoTypelist;
            case 10://自动选择本部门内符合条件所有人
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        department = departmentService.getDeptById(users.getDeptId());
                        list = usersService.getUsersByDeptId(department.getDeptId());
                        for (Users users1 : list) {
                            if (flowProcess.getPrcsUser() != null && flowProcess.getPrcsUser().contains(users1.getUserId()) ||
                                    flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptId().toString()) ||
                                    flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPriv().toString()) ||
                                    flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptIdOther()) ||
                                    flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPrivOther())) {
                                autoTypelist.add(users1);
                            }
                        }
                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users u1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getDeptById(u1.getDeptId());
                            list = usersService.getUsersByDeptId(department.getDeptId());
                            for (Users users1 : list) {
                                if (flowProcess.getPrcsUser() != null && flowProcess.getPrcsUser().contains(users1.getUserId()) ||
                                        flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptId().toString()) ||
                                        flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPriv().toString()) ||
                                        flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptIdOther()) ||
                                        flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPrivOther())) {
                                    autoTypelist.add(users1);
                                }
                            }
                        }
                    }
                }
                return autoTypelist;
            case 11://自动选择本一级部门内符合条件所有人员
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        department = departmentService.getFatherDept(users.getDeptId());
                        list = usersService.getUsersByDeptId(department.getDeptId());
                        for (Users users1 : list) {
                            if (flowProcess.getPrcsUser() != null && flowProcess.getPrcsUser().contains(users1.getUserId()) ||
                                    flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptId().toString()) ||
                                    flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPriv().toString()) ||
                                    flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptIdOther()) ||
                                    flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPrivOther())) {
                                autoTypelist.add(users1);
                            }
                        }
                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users u1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getFatherDept(u1.getDeptId());
                            list = usersService.getUsersByDeptId(department.getDeptId());
                            for (Users users1 : list) {
                                if (flowProcess.getPrcsUser() != null && flowProcess.getPrcsUser().contains(users1.getUserId()) ||
                                        flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptId().toString()) ||
                                        flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPriv().toString()) ||
                                        flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptIdOther()) ||
                                        flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPrivOther())) {
                                    autoTypelist.add(users1);
                                }
                            }
                        }
                    }
                }
                return autoTypelist;
            case 12://自动选择指定部门主管
                if (!StringUtils.checkNull(flowProcess.getAutoDept())) {
                    department = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                    if (!StringUtils.checkNull(department.getManager())) {
                        autoTypelist = usersService.getUserByuserId(department.getManager());
                    }
                    if (autoTypelist.size() == 1) {
                        for (Users users1 : autoTypelist) {
                            users1.setOpFlag("1");
                        }
                    }
                }
                return autoTypelist;
            case 13://自动选择指定部门助理
                if (!StringUtils.checkNull(flowProcess.getAutoDept())) {
                    department = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                    if (!StringUtils.checkNull(department.getAssistantId())) {
                        autoTypelist = usersService.getUserByuserId(department.getAssistantId());
                    }
                    if (autoTypelist.size() == 1) {
                        for (Users users1 : autoTypelist) {
                            users1.setOpFlag("1");
                        }
                    }
                }

                return autoTypelist;
            case 14://自动选择指定部门上级主管领导
                if (!StringUtils.checkNull(flowProcess.getAutoDept())) {
                    department = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                    //dparent = departmentService.getDeptById(department.getDeptParent());
                    if (!StringUtils.checkNull(department.getLeader1())) {
                        autoTypelist = usersService.getUserByuserId(department.getLeader1());
                    }
                    if (autoTypelist.size() == 1) {
                        for (Users users1 : autoTypelist) {
                            users1.setOpFlag("1");
                        }
                    }
                }
                return autoTypelist;
            case 15://自动选择指定部门上级分管领导
                department = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                // dparent = departmentService.getDeptById(department.getDeptParent());
                if (!StringUtils.checkNull(department.getLeader2())) {
                    autoTypelist = usersService.getUserByuserId(department.getLeader2());
                }
                if (autoTypelist.size() == 1) {
                    for (Users users1 : autoTypelist) {
                        users1.setOpFlag("1");
                    }
                }
                return autoTypelist;
            default:
                return autoTypelist;
        }
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年4月30日 上午9:52:22
     * 方法介绍:   删除工作流附件
     * 参数说明    @param runid 流程实例id
     * 参数说明:   @param aid 附件主键
     * 参数说明:   @param module 模块
     * 参数说明:   @param ym 年月
     * 参数说明:   @param attachmentId 附件id
     * 参数说明:   @param attachmenrName 附件名字
     * 参数说明:   @param company 公司
     * 参数说明:   @param response 响应
     * 参数说明:   @param request 请求
     * 参数说明:   @return
     */
    public ToJson delete(String runId,
                         @RequestParam("AID") String aid,
                         @RequestParam("MODULE") String module,
                         @RequestParam("YM") String ym,
                         @RequestParam("ATTACHMENT_ID") String attachmentId,
                         @RequestParam("ATTACHMENT_NAME") String attachmentName,
                         @RequestParam("COMPANY") String company,
                         HttpServletResponse response,
                         HttpServletRequest request) {
        ToJson tj = new ToJson();
        try {
            FlowRun flowRun = wfeFlowRun.find(Integer.parseInt(runId));
            StringBuffer id = new StringBuffer();
            StringBuffer name = new StringBuffer();
            attachmentName = URLDecoder.decode(attachmentName, "UTF-8");
            tj = enclosureService.delete(aid, module, ym, attachmentId, attachmentName, company, response, request);
            if (tj.isFlag()) {
                if (flowRun.getAttachmentId() != "" || flowRun.getAttachmentName() != "") {
                    String[] attachmentIds = flowRun.getAttachmentId().split(",");
                    String[] attachName = flowRun.getAttachmentName().split("\\*");
                    List<String> idsList = new ArrayList<String>();
                    Collections.addAll(idsList, attachmentIds);
                    List<String> nameList = new ArrayList<String>();
                    Collections.addAll(nameList, attachName);
                    for (int i = 0; i < attachmentIds.length; i++) {
                        String yaid = attachmentIds[i].substring(0, attachmentIds[i].indexOf('@'));
                        if (yaid.equals(aid)) {
                            idsList.remove(attachmentIds[i]);
                            attachmentIds = idsList.toArray(new String[0]);
                            break;
                        }
                    }
                    for (int j = 0; j < attachName.length; j++) {
                        String yattachName = attachName[j];
                        if (yattachName.equals(attachmentName)) {
                            nameList.remove(attachName[j]);
                            attachName = nameList.toArray(new String[0]);
                            break;
                        }
                    }

                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("runId", runId);
                    map.put("attachmentId", org.apache.commons.lang3.StringUtils.join(attachmentIds, ","));
                    map.put("attachmentName", org.apache.commons.lang3.StringUtils.join(attachName, "*"));
                    wfeFlowRun.updateAttachment(map);
                }
                tj.setFlag(0);
                tj.setMsg("true");
                return tj;
            }
            tj.setFlag(1);
            tj.setMsg("false");
            return tj;
        } catch (Exception e) {
            L.e("delete" + e);
            tj.setFlag(1);
            tj.setMsg("false");
            return tj;
        }
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   查询回退之前步骤
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param allowBack  回退状态
     * 参数说明:   @param prcsId  步骤id
     * 参数说明:   @return
     *
     * @return ToJson<FlowFast>
     */
    public ToJson<FlowRunPrcs> getflowprcsdata(String allowBack, String runId, String prcsId, String userId) {
        ToJson<FlowRunPrcs> toJson = new ToJson<FlowRunPrcs>();
        Map<String, Object> m = new HashMap<String, Object>();
        try {
            switch (Integer.parseInt(allowBack)) {
                case 1:
                    m.put("prcsId", Integer.parseInt(prcsId) - 1);
                    m.put("runId", runId);
                    List<FlowRunPrcs> listFloRunPrcs = wfeFlowRunPrcs.findByRunId(m);
                    for (FlowRunPrcs flowRunPrcs : listFloRunPrcs) {
                        if (flowRunPrcs.getPrcsTime().contains(".")) {
                            flowRunPrcs.setPrcsTime(flowRunPrcs.getPrcsTime().substring(0, flowRunPrcs.getPrcsTime().length() - 2));
                        }
                    }
                    toJson.setObj(listFloRunPrcs);
                    toJson.setMsg("true");
                    toJson.setFlag(0);
                    return toJson;
                case 2:
                    m.put("prcsId", prcsId);
                    m.put("runId", runId);
                    m.put("userId", userId);

                    //用来存储回退的流程实例
                    List<FlowRunPrcs> back = wfeFlowRunPrcs.getfrpByrollBack(m);

                    for (FlowRunPrcs flowRunPrcs : back) {
                        if (flowRunPrcs.getPrcsTime().contains(".")) {
                            flowRunPrcs.setPrcsTime(flowRunPrcs.getPrcsTime().substring(0, flowRunPrcs.getPrcsTime().length() - 2));
                        }
                    }
                 /*   List<FlowRunPrcs> relist = new ArrayList<FlowRunPrcs>();
                    List<FlowRunPrcs> reAll = this.reFrp(list, relist, frp);
                   Set<FlowRunPrcs> set = new HashSet<FlowRunPrcs>(reAll);
                   reAll = new ArrayList<FlowRunPrcs>(set);*/

                    //排序
                    Collections.sort(back, new Comparator<FlowRunPrcs>() {
                        @Override
                        public int compare(FlowRunPrcs o1, FlowRunPrcs o2) {
                            int i = o1.getPrcsId() - o2.getPrcsId();
                            if (i == 0) {
                                return o1.getFlowPrcs() - o2.getFlowPrcs();
                            }
                            return i;
                        }
                    });

                    try {
                        if (runId != null && !("").equals(runId)) {
                            if (back != null && back.size() > 0) {
                                List<FlowRunPrcs> backNoSonFlowRun = new ArrayList<FlowRunPrcs>();
                                for (int i = 0; i < back.size(); i++) {
                                    if (back.get(i).getFlowProcess().getChildFlow() == 0) {
                                        backNoSonFlowRun.add(back.get(i));
                                    }
                                }
                                if (backNoSonFlowRun != null && backNoSonFlowRun.size() > 0) {
                                    toJson.setObj(backNoSonFlowRun);
                                    toJson.setFlag(0);
                                    toJson.setMsg("true");
                                    return toJson;
                                }
                            }

                        }
                    } catch (Exception e) {
                        toJson.setObj(back);
                        toJson.setFlag(0);
                        toJson.setMsg("true");
                        return toJson;
                    }

                    toJson.setObj(back);
                    toJson.setFlag(0);
                    toJson.setMsg("true");
                    return toJson;
            }
        } catch (Exception e) {
            L.e("getflowprcsdate" + e.getMessage());
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
            return toJson;
        }
        toJson.setFlag(0);
        toJson.setMsg("true");
        return toJson;
    }


    public List<FlowRunPrcs> reFrp(List<FlowRunPrcs> list, List<FlowRunPrcs> relist, FlowRunPrcs flowRunPrcs) {
        for (FlowRunPrcs frp : list) {
            String flowPrcs = frp.getFlowPrcs().toString();
            if (flowRunPrcs.getParent().indexOf(flowPrcs) != -1) {
                relist.add(frp);
                if ("0".equals(frp.getParent())) {
                    return relist;
                }
                reFrp(list, relist, frp);
                continue;
            }

        }
        return relist;
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   回退步骤插入
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param flowPrcs 回退流程步骤id
     * 参数说明:   @param prcsId  当前流程实例步骤id
     * 参数说明:   @param flowStep  当前流程步骤id
     * 参数说明:   @return
     *
     * @return
     */
    public AjaxJson insertprcsdata(String runId, String flowStep, String prcsId, String flowPrcs, Users users, String feedback) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> maps = new HashMap<String, Object>();
        try {
            maps.put("prcsId", flowStep);
            maps.put("runId", runId);
            maps.put("prcsFlag", "3");
            maps.put("deliverTime", DateFormat.getStrDate(new Date()));
            maps.put("userId", users.getUserId());
            wfeFlowRunPrcs.updateSql(maps);
            maps.put("flowPrcs", prcsId);
            //maps.put("userId", users.getUserId());
            List<FlowRunPrcs> thislistFrp = wfeFlowRunPrcs.selectCondition(maps);
            //当前流程实例步骤
            FlowRunPrcs flowRunPrcs1 = thislistFrp.get(0);
            maps.put("prcsId", flowPrcs);
            maps.remove("flowPrcs");
            maps.remove("userId");
            maps.remove("prcsFlag");
            List<FlowRunPrcs> listFloRunPrcs = wfeFlowRunPrcs.findByRunId(maps);
            if (listFloRunPrcs.size() == 0) {
                maps.put("opFlag", 0);
                listFloRunPrcs = wfeFlowRunPrcs.selectCondition(maps);
                maps.remove("opFlag");
            }
            //回退流程实例步骤
            FlowRunPrcs fp = listFloRunPrcs.get(0);
            FlowRun flowRun = wfeFlowRun.find(Integer.parseInt(runId));

            FlowRunPrcs flowRunPrcs = new FlowRunPrcs();
            flowRunPrcs.setRunId(Integer.parseInt(runId));
            //flowRunPrcs.setPrcsId(flowProcess.getPrcsId());
            flowRunPrcs.setPrcsId(Integer.parseInt(flowStep) + 1);
            flowRunPrcs.setUserId(fp.getUserId());
            flowRunPrcs.setPrcsDept(users.getDeptId());
            flowRunPrcs.setParentPrcsId(String.valueOf(flowRunPrcs1.getPrcsId()));
            flowRunPrcs.setPrcsFlag("1");
            flowRunPrcs.setFlowPrcs(fp.getFlowPrcs());
            flowRunPrcs.setOpFlag(fp.getOpFlag());
            flowRunPrcs.setTopFlag(fp.getTopFlag());
            flowRunPrcs.setCreateTime(DateFormat.getStrDate(new Date()));
            flowRunPrcs.setPrcsTime(DateFormat.getStrDate(new Date()));
            flowRunPrcs.setDeliverTime("0000-00-00 00:00:00");
            flowRunPrcs.setActiveTime("0000-00-00 00:00:00");
            flowRunPrcs.setBackFlowPrcs(fp.getFlowPrcs());
            flowRunPrcs.setBackPrcsId(fp.getPrcsId());
            flowRunPrcs.setParent(String.valueOf(thislistFrp.get(0).getFlowPrcs()));

            /** lr    工作流操作添加日志信息 ----回退        **/

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
            flowRunLog.setType(Constant.TYPE3);
            flowRunLog.setRunId(flowRunPrcs.getRunId());
            flowRunLog.setPrcsId(flowRunPrcs.getPrcsId());
            flowRunLog.setGoProcsId(flowPrcs);

            Integer flowId = flowRunLogMapper.selectFlowRunLogByRunId(Integer.parseInt(runId)).getFlowId();
            String flowName = flowRunLogMapper.selectPrcsName(Integer.parseInt(prcsId), flowId);
            flowRunLog.setFlowName(flowName);
            wfeLog.addFlowRunLog(flowRunLog);
            /**                  添加完毕                **/

            wfeFlowRunPrcs.save(flowRunPrcs);
            if (!StringUtils.checkNull(feedback)) {
                ToJson<FlowRunFeedback> json = this.workfeedback(feedback, runId, flowStep, String.valueOf(flowRunPrcs1.getFlowPrcs()), users.getUserId(), "2");
            }
            /*HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes())
                    .getRequest();*/
            //发送事务提醒
            String tableName = request.getParameter("tableName");
            String tabId = request.getParameter("tabId");
            workService.todoWorkSmsBoby(fp.getUserId(), String.valueOf(fp.getFlowPrcs()), tableName, runId, flowRun.getRunName(), String.valueOf(flowRun.getFlowId()), flowStep, null, tabId, null, feedback, request, "1", users, null, fp.getUserId(), "");
            //主办人提交消除事物提醒（结束流程时没有主办人）
            //String[] strs1 = flowPrcs.split(",");

            if ("document".equals(tableName)) {
                String smsUrl = "/workflow/work/workform?opflag=1&flowId=" + flowId + "&flowStep=" + prcsId + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + flowPrcs + "&isNomalType=false";
                smsService.updatequerySmsByType("70", users.getUserId(), smsUrl.trim());
            } else if ("document".equals(tableName)) {
                String smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowRun.getFlowId()) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + prcsId + "&tableName=budget";
                smsService.updatequerySmsByType("7", users.getUserId(), smsUrl.trim());
            } else {
                String smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowRun.getFlowId()) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + prcsId;
                smsService.updatequerySmsByType("7", users.getUserId(), smsUrl.trim());
            }

            ajaxJson.setObj(flowRunPrcs);
            ajaxJson.setMsg("true");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            L.e("insertprcsDate" + e.getMessage());
            ajaxJson.setMsg("false");
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }


    /**
     * 因种种原因，临时处理，暂定回退插入流为一步，后期完善可根据backId获取回退步骤的经办人等数据
     *
     * @param id       flow_run_prcs 表主键id
     * @param backId   回退的主键id
     * @param users    当前用户
     * @param feedback 回退会签意见
     * @return
     */
    public AjaxJson insertprcsdata(Integer id, Integer backId, Users users, String feedback) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            //当前流程实例
            FlowRunPrcs currentFrp = wfeFlowRunPrcs.selectByPrimaryKey(id);
            //要回退的流程实例
            FlowRunPrcs backFrp = wfeFlowRunPrcs.selectByPrimaryKey(backId);
            FlowRunPrcs flowRunPrcs = new FlowRunPrcs();
            flowRunPrcs.setId(id);
            flowRunPrcs.setPrcsFlag("3");
            flowRunPrcs.setDeliverTime(DateFormat.getStrDate(new Date()));
            flowRunPrcs.setPrcsTime("");
            wfeFlowRunPrcs.updateFrpById(flowRunPrcs);

            //当前的
            Integer runId = currentFrp.getRunId();
            Integer currentPrcsId = currentFrp.getPrcsId();
            Integer currentFlowPrcs = currentFrp.getFlowPrcs();
            //要退回的
            Integer backPrcsId = backFrp.getPrcsId();
            Integer backFlowPrcs = backFrp.getFlowPrcs();

            FlowRun flowRun = wfeFlowRun.find(runId);

            //强制转交处理经办人流程状态
            wfeFlowRunPrcs.updateHandler(runId, currentPrcsId, currentFlowPrcs, "4", null,
                    DateFormat.getStrDate(new Date()), null);

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", users.getUserId());
            map.put("runId", flowRun.getRunId());
            map.put("prcsId", currentFrp.getPrcsId() + 1);
            map.put("flowPrcs", backFlowPrcs);
            List<FlowRunPrcs> listFrp = wfeFlowRunPrcs.findByRunIdTopFlag(map);
            if (listFrp != null && listFrp.size() > 0) {


            } else {
                flowRunPrcs = new FlowRunPrcs();
                flowRunPrcs.setRunId(runId);
                flowRunPrcs.setPrcsId(currentFrp.getPrcsId() + 1);
                flowRunPrcs.setFlowPrcs(backFlowPrcs);
                flowRunPrcs.setOpFlag(backFrp.getOpFlag());
                flowRunPrcs.setTopFlag(backFrp.getTopFlag());
                flowRunPrcs.setUserId(backFrp.getUserId());
                flowRunPrcs.setPrcsDept(backFrp.getPrcsDept());
                flowRunPrcs.setParent(currentFlowPrcs.toString());
                flowRunPrcs.setParentPrcsId(currentPrcsId.toString());
                flowRunPrcs.setPrcsFlag("1");
                flowRunPrcs.setCreateTime(DateFormat.getStrDate(new Date()));
                flowRunPrcs.setPrcsTime("0000-00-00 00:00:00");
                flowRunPrcs.setDeliverTime("0000-00-00 00:00:00");
                flowRunPrcs.setActiveTime("0000-00-00 00:00:00");
                flowRunPrcs.setBackFlowPrcs(backFlowPrcs);
                flowRunPrcs.setBackPrcsId(backPrcsId);
                wfeFlowRunPrcs.save(flowRunPrcs);
            }

            if (!StringUtils.checkNull(feedback)) {
                ToJson<FlowRunFeedback> json = this.workfeedback(feedback, runId.toString(), currentFrp.getPrcsId().toString(), currentFrp.getFlowPrcs().toString(), users.getUserId(), "2");
            }

            // lr    工作流操作添加日志信息 ----回退
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            wfeLog.getFlowRunLogByRequest(request, runId, flowRun.getFlowId(), currentFrp.getPrcsId(),
                    currentFrp.getFlowPrcs(), backFrp.getFlowPrcs().toString(), Constant.TYPE3);
            //        添加完毕

            //发送事务提醒
            String tableName = request.getParameter("tableName");
            String tabId = request.getParameter("tabId");
            workService.todoWorkSmsBoby(flowRunPrcs.getUserId(), backFlowPrcs.toString(), tableName, runId.toString(), flowRun.getRunName(), String.valueOf(flowRun.getFlowId()), currentPrcsId.toString(), null, tabId, null, feedback, request, "1", users, null, flowRunPrcs.getUserId(), "");
            //主办人提交消除事物提醒（结束流程时没有主办人）
            //String[] strs1 = flowPrcs.split(",");

            if ("document".equals(tableName)) {
                String smsUrl = "/workflow/work/workform?opflag=1&flowId=" + flowRun.getFlowId() + "&flowStep=" + currentPrcsId + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + currentFlowPrcs + "&isNomalType=false";
                smsService.updatequerySmsByType("70", users.getUserId(), smsUrl.trim());
            } else if ("document".equals(tableName)) {
                String smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowRun.getFlowId()) + "&flowStep=" + currentPrcsId + "&runId=" + runId + "&prcsId=" + currentFlowPrcs + "&tableName=budget";
                smsService.updatequerySmsByType("7", users.getUserId(), smsUrl.trim());
            } else {
                String smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowRun.getFlowId()) + "&flowStep=" + currentPrcsId + "&runId=" + runId + "&prcsId=" + currentFlowPrcs;
                smsService.updatequerySmsByType("7", users.getUserId(), smsUrl.trim());
            }

            /*********回退触发器**************/
            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse");
            if (StringUtils.checkNull((String) request.getSession().getAttribute(
                    "loginDateSouse"))) {
                sqlType = "xoa1001";
            }
            //触发器参数提取处公共方法
            TriggerPlugIn triggerPlugIn = this.getTrigger(runId.toString(), String.valueOf(flowRun.getFlowId()), sqlType, flowRun.getBeginUser(), flowRun.getBeginTime(),
                    flowRun.getRunName(), backFlowPrcs.toString(), currentPrcsId.toString(), currentFlowPrcs.toString(), tabId, request, back);
            //触发器执行
            this.notifyNotice(triggerPlugIn);

            //ajaxJson.setObj(flowRunPrcs);
            ajaxJson.setMsg("true");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            L.e("insertprcsDate" + e.getMessage());
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }


    //导出表单
    public void exportExcel(Users users, String type, HttpServletResponse response, HttpServletRequest request) {
        List<FlowRunPrcs> resultList = new ArrayList<FlowRunPrcs>();
        if ("1".equals(type)) {
            resultList = this.getReceivedWorksList(users);
        } else if ("2".equals(type)) {
            resultList = this.getHandledWorksList(users);
        } else if ("3".equals(type)) {
            resultList = this.getAllWorksList(users);
        } else if ("4".equals(type)) {
            //resultList = getViewsWorksList(params, loginUser);
            resultList = this.getEntrustWorkList(request);
        } else if ("5".equals(type)) {
            //resultList = getSuspendedWorksList(params, loginUser);
        }

        // 获取当前时间
        Calendar c = Calendar.getInstance();
        String time = "" + c.get(Calendar.YEAR) + (c.get(Calendar.MONTH) + 1)
                + c.get(Calendar.DAY_OF_MONTH) + c.get(Calendar.HOUR_OF_DAY)
                + c.get(Calendar.MINUTE);

        try {
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("工作查询列表信息");
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow((int) 0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short) 12); // 字体高度
            font.setColor(HSSFFont.COLOR_NORMAL); // 字体颜色
            font.setFontName("宋体"); // 字体
            font.setBold(true); // 宽度
            font.setItalic(false); // 是否使用斜体
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
            style.setFont(font);

            HSSFFont font1 = wb.createFont();
            font1.setFontHeightInPoints((short) 12); // 字体高度
            font1.setColor(HSSFFont.COLOR_NORMAL); // 字体颜色
            font1.setFontName("宋体"); // 字体
            font1.setBold(true); // 宽度
            font1.setItalic(false); // 是否使用斜体
            HSSFCellStyle style1 = wb.createCellStyle();
            style1.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
            style1.setFont(font1);

            HSSFCell cell = row.createCell((short) 0);
            List<String> head = new ArrayList<String>();

            StringBuffer stringBuffer = new StringBuffer();

            String[] d = {"流水号", "流程名称", "当前步骤", "发起人", "状态", "到达时间", "已停留"};
            ;//待办
            String[] b = {"流水号", "流程名称", "工作名称/文号", "发起人", "办结时间", "流程状态"};//办结
            String[] q = {"流水号", "流程名称", "工作名称/文号", "发起人", "办结时间", "流程状态"};//全部
            String[] w = {"流水号", "流程名称", "我经办的步骤", "当前经办人", "办结时间", "流程状态"};//委托

            if ("1".equals(type)) {
                for (int i = 0; i < d.length; i++) {
                    cell.setCellValue(d[i]);
                    cell.setCellStyle(style);
                    cell = row.createCell((short) (i + 1));
                }
                // 设置内容
                Map map = new HashMap();
                for (int m = 0; m < resultList.size(); m++) {
                    HSSFRow r = sheet.createRow((int) (m + 1));
                    //map = (Map) resultList.get(m);
                    FlowRunPrcs flowRunPrcs = resultList.get(m);
                    map.put(0, flowRunPrcs.getRunId());
                    map.put(1, flowRunPrcs.getFlowRun().getRunName());
                    map.put(2, "第" + flowRunPrcs.getPrcsId() + "步:" + flowRunPrcs.getFlowProcess().getPrcsName());
                    map.put(3, flowRunPrcs.getUserName());
                    map.put(4, returnFlag(flowRunPrcs.getPrcsFlag()));
                    map.put(5, flowRunPrcs.getReceiptTime());
                    map.put(6, flowRunPrcs.getArriveTime());
                    for (int n = 0; n < map.size(); n++) {
                        cell = r.createCell((short) (n));
                        cell.setCellValue(String.valueOf(map.get(n)));
                        cell.setCellStyle(style1);
                    }
                }
                stringBuffer.append("待办工作列表").append(time.toString()).append(".xls");
            }
            if ("2".equals(type)) {
                for (int i = 0; i < b.length; i++) {
                    cell.setCellValue(b[i]);
                    cell.setCellStyle(style);
                    cell = row.createCell((short) (i + 1));
                }

                // 设置内容
                Map map = new HashMap();
                for (int m = 0; m < resultList.size(); m++) {
                    HSSFRow r = sheet.createRow((int) (m + 1));
                    //map = (Map) resultList.get(m);
                    FlowRunPrcs flowRunPrcs = resultList.get(m);
                    map.put(0, flowRunPrcs.getRunId());
                    map.put(1, flowRunPrcs.getFlowRun().getRunName());
                    map.put(2, "第" + flowRunPrcs.getFlowProcess().getPrcsId() + "步:" + flowRunPrcs.getFlowProcess().getPrcsName());
                    map.put(3, flowRunPrcs.getUserName());
                    map.put(4, flowRunPrcs.getDeliverTime());
                    map.put(5, returnFlag(flowRunPrcs.getPrcsFlag()));
                    for (int n = 0; n < map.size(); n++) {
                        cell = r.createCell((short) (n));
                        cell.setCellValue(String.valueOf(map.get(n)));
                        cell.setCellStyle(style1);
                    }
                }
                stringBuffer.append("办结工作列表").append(time.toString()).append(".xls");
            }
            if ("3".equals(type)) {
                for (int i = 0; i < b.length; i++) {
                    cell.setCellValue(b[i]);
                    cell.setCellStyle(style);
                    cell = row.createCell((short) (i + 1));
                }

                // 设置内容
                Map map = new HashMap();
                for (int m = 0; m < resultList.size(); m++) {
                    HSSFRow r = sheet.createRow((int) (m + 1));
                    //map = (Map) resultList.get(m);
                    FlowRunPrcs flowRunPrcs = resultList.get(m);
                    map.put(0, flowRunPrcs.getRunId());
                    map.put(1, flowRunPrcs.getFlowType().getFlowName());
                    map.put(2, flowRunPrcs.getFlowRun().getRunName());
                    map.put(3, flowRunPrcs.getUserName());
                    map.put(4, "第" + flowRunPrcs.getFlowProcess().getPrcsId() + "步:" + flowRunPrcs.getFlowProcess().getPrcsName());
                    map.put(5, returnFlag(flowRunPrcs.getPrcsFlag()));
                    for (int n = 0; n < map.size(); n++) {
                        cell = r.createCell((short) (n));
                        cell.setCellValue(String.valueOf(map.get(n)));
                        cell.setCellStyle(style1);
                    }
                }
                stringBuffer.append("全部工作列表").append(time.toString()).append(".xls");
            }
            if ("4".equals(type)) {
                for (int i = 0; i < w.length; i++) {
                    cell.setCellValue(w[i]);
                    cell.setCellStyle(style);
                    cell = row.createCell((short) (i + 1));
                }

                // 设置内容
                Map map = new HashMap();
                for (int m = 0; m < resultList.size(); m++) {
                    HSSFRow r = sheet.createRow((int) (m + 1));
                    FlowRunPrcs flowRunPrcs = resultList.get(m);
                    map.put(0, flowRunPrcs.getRunId());
                    map.put(1, flowRunPrcs.getFlowRun().getRunName());
                    map.put(2, "第" + flowRunPrcs.getFlowProcess().getPrcsId() + "步:" + flowRunPrcs.getFlowProcess().getPrcsName());
                    map.put(3, flowRunPrcs.getUserName());
                    map.put(4, flowRunPrcs.getDeliverTime());
                    map.put(5, returnFlag(flowRunPrcs.getPrcsFlag()));
                    for (int n = 0; n < map.size(); n++) {
                        cell = r.createCell((short) (n));
                        cell.setCellValue(String.valueOf(map.get(n)));
                        cell.setCellStyle(style1);
                    }
                }
                stringBuffer.append("委托工作列表").append(time.toString()).append(".xls");
            }


            // 设置每一列的宽度
            sheet.setDefaultColumnWidth(15);
            String fileName = stringBuffer.toString();
            response.setHeader("Content-disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //查询办结流程列表
    public List<FlowRunPrcs> getHandledWorksList(Users users) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("userId", users.getUserId());
        ToJson<FlowRunPrcs> toJson = wfeFlowRunPrcs.selectEnd(maps, null, null, false);
        List<FlowRunPrcs> list = toJson.getObj();
        return list;
    }


    //查询待办流程列表
    public List<FlowRunPrcs> getReceivedWorksList(Users users) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("userId", users.getUserId());
        ToJson<FlowRunPrcs> toJson = wfeFlowRunPrcs.selectObject(maps, null, null, false);
        List<FlowRunPrcs> list = toJson.getObj();
        return list;
    }

    //查询全部工作
    public List<FlowRunPrcs> getAllWorksList(Users users) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("userId", users.getUserId());
        ToJson<FlowRunPrcs> toJson = wfeFlowRunPrcs.selectAll(maps, null, null, false);
        List<FlowRunPrcs> list = toJson.getObj();
        return list;
    }

    //查询委托工作
    public List<FlowRunPrcs> getEntrustWorkList(HttpServletRequest request) {
        PageParams fe = new PageParams();
        fe.setUseFlag(false);
        ToJson<FlowRunPrcs> toJson = wfeFlowRunPrcs.entrustWorkList(request, fe);
        List<FlowRunPrcs> list = toJson.getObj();
        return list;
    }


    public String returnFlag(String prcsFlag) {
        if (("1").equals(prcsFlag)) {
            return "未接收";
        }
        if (prcsFlag.equals("2")) {
            return "办理中";
        }
        if (prcsFlag.equals("3")) {
            return "转交下一步，下一步经办人无人接收";
        }
        if (prcsFlag.equals("4")) {
            return "已办结";
        }
        if (prcsFlag.equals("5")) {
            return "自由流程预设步骤";
        }
        if (prcsFlag.equals("6")) {
            return "已挂起";
        }
        return "";
    }


    /**
     * 创建作者:   季佳伟
     * 创建日期:   2017/8/23 16:50
     * 方法介绍:   根据前台传入的runId,prcsId,toId,flowPrcs,opFlag,从session中获取users
     * 参数说明:
     *
     * @return
     */
    public ToJson<FlowRunPrcs> entrust(String runId, String prcsId, String toId,
                                       String flowPrcs, String opFlag, Users users) {
        ToJson<FlowRunPrcs> json = new ToJson<FlowRunPrcs>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("runId", runId);
            map.put("prcsId", prcsId);
            map.put("prcsFlag", 4);
            map.put("opFlag", 0);
            wfeFlowRunPrcs.updateSql(map);
            FlowRunPrcs flowRunPrcs = new FlowRunPrcs();
            flowRunPrcs.setRunId(Integer.parseInt(runId));
            flowRunPrcs.setPrcsId(Integer.parseInt(prcsId));
            flowRunPrcs.setFlowPrcs(Integer.parseInt(flowPrcs));
            flowRunPrcs.setUserId(toId);
            flowRunPrcs.setPrcsFlag("1");
            flowRunPrcs.setOpFlag("1");
            flowRunPrcs.setOtherUser(users.getUserId() + ",");
            wfeFlowRunPrcs.save(flowRunPrcs);
            json.setMsg("true");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("error");
        }
        return json;
    }


    //工作关注
    public AjaxJson workAttention(Integer runId, String userId, String status) {
        AjaxJson ajaxJson = new AjaxJson();
        FlowRun flowRun = wfeFlowRun.find(runId);
        String focusUser = flowRun.getFocusUser();
        if (status.equals("0")) {
            focusUser = focusUser.replaceAll(userId, "");
        } else {
            focusUser = focusUser + userId;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("runId", runId);
        map.put("userId", focusUser);
        map.put("status", status);
        try {
            int a = wfeFlowRun.updateState(map);
            if (a > 0) {
                ajaxJson.setFlag(true);
                ajaxJson.setMsg("OK");
            } else {
                ajaxJson.setFlag(false);
                ajaxJson.setMsg("false");
            }
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
        }
        return ajaxJson;
    }


    //工作结束和工作删除,状态值0为工作结束1为工作删除
    public AjaxJson worDelete(Integer runId, String status) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            if (status.equals("0")) {
                String endTime = DateFormat.getStrDate(new Date());//设置日期格式
                map.put("runId", runId);
                map.put("endTime", endTime);
                wfeFlowRun.updateState(map);
            } else {
                map.put("runId", runId);
                map.put("delFlag", 1);
                wfeFlowRun.updateState(map);
            }
            ajaxJson.setMsg("OK");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }


    public AjaxJson saveHandle(Integer runId, Integer prcsId, String flowPrcs, Users users) {
        AjaxJson ajaxJson = new AjaxJson();
        FlowRun flowRun = wfeFlowRun.find(runId);
        List<FlowRunPrcs> list = wfeFlowRunPrcs.selectFind(prcsId, runId, Integer.parseInt(flowPrcs), users.getUserId(), null);
        FlowRunPrcs frp = list.get(0);
        //判断会签是否是无主办人会签情况
        Map<String, Object> map = new HashMap();
        map.put("runId", runId);
        map.put("opFlag", 0);
        map.put("prcsId", prcsId);
        map.put("flowPrcs", flowPrcs);

        // 更新flowAssign
        try {
            List<FlowAssignWithBLOBs> assign = flowAssignMapper.getAssign(runId, prcsId, flowPrcs, users.getUserId());
            if (null != assign) {
                for (FlowAssignWithBLOBs assign1 : assign) {
                    flowAssignMapper.updateStatus(assign1.getAssignId());
                }
            }
        } catch (Exception e) {

        }
        //判断该流程是否是多人无主办人办理
        List<FlowRunPrcs> flowRunPrcs = wfeFlowRunPrcs.selectFind(map);
        if ("2".equals(frp.getTopFlag())) {
            //查询无主办人是否是最后一个进入该页面
            int count = 0;
            int result = flowRunPrcs.size();
            if (result > 0) {
                for (FlowRunPrcs f : flowRunPrcs) {
                    if (Integer.parseInt(f.getPrcsFlag()) > 2) {
                        count++;
                    }
                }

                if (result >= 1) {//存在多个无主办人同时办理的情况
                    int flag = result - count;
                    if (result == 1 || flag == 1) {
                        //是最后一个无主办人办理
                        ajaxJson.setFlag(false);
                        ajaxJson.setMsg("该用户是最后一个无主办人");
                        return ajaxJson;
                    }
                }
            }
        }

        boolean bol = false;
        SysPara myproject = sysParaMapper.querySysPara("MYPROJECT");
        if (myproject != null && !StringUtils.checkNull(myproject.getParaValue())
                && "dazu".equals(myproject.getParaValue())) {
            bol = true;
        }

        //不存在两个无主办人同时办理的情况,正常办结
        Map<String, Object> maps = new HashMap<String, Object>();
        try {
            maps.put("prcsId", prcsId);
            maps.put("runId", runId);
            maps.put("prcsFlag", "4");
            maps.put("deliverTime", DateFormat.getStrDate(new Date()));
            maps.put("userId", users.getUserId());
            //应对并发
            maps.put("flowPrcs", flowPrcs);
            maps.put("comment", "1");//办公门户显示效果状态值
            wfeFlowRunPrcs.updateHandleWithComment(maps);
            //判断是否有会签人，有则发送事务提醒
            Map<String, Object> map1 = new HashMap();
            map1.put("runId", runId);
            map1.put("prcsId", prcsId);
            map1.put("flowPrcs", flowPrcs);
            map1.put("userId", users.getUserId());
            FlowRunPrcs flowRunPrcs1 = flowRunPrcsMapper.selectbyOpaddUser(map1);
            if (flowRunPrcs1 != null) {
                DocumentModel documentModel = documentSerivce.checkRunId(flowRunPrcs1.getRunId());
                Map<String, Object> map2 = new HashMap();
                map2.put("runId", runId);
                map2.put("prcsId", prcsId);
                map2.put("flowPrcs", flowPrcs);
                map2.put("userId", flowRunPrcs1.getOpaddUser());
                List<FlowRunPrcs> frp2 = wfeFlowRunPrcs.selectFind(map2);
                String opFlag = frp2.get(0).getOpFlag();
                SmsBody smsBody = new SmsBody();
                String title = "";
                String context = "";
                if (documentModel != null) {
                    title = bol ? flowRun.getRunName() : "您有新的公文需要签阅";
                    context = "流水号：" + runId + "，公文文号：" + flowRun.getRunName();
                    String remindUrl = "/workflow/work/workform?opflag=" + opFlag + "&flowId=" + flowRun.getFlowId() + "&flowStep=" + prcsId + "&tableName=document&tabId=" + documentModel.getId() + "&runId=" + runId + "&prcsId=" + flowPrcs + "&isNomalType=false";
                    smsBody = new SmsBody(users.getUserId(), "70", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, context);
                } else {
                    title = bol ? flowRun.getRunName() : "您有新的工作需要办理";
                    context = "/workflow/work/workform?opflag=" + opFlag + "&flowId=" + flowRun.getFlowId() + "&flowStep=" + (prcsId) + "&runId=" + runId + "&prcsId=" + flowPrcs;
                    String smsContent = "流水号：" + runId + "，工作名称/文号：" + flowRun.getRunName();
                    smsBody = new SmsBody(users.getUserId(), "7", DateFormat.getTime(DateFormat.getCurrentTime()), context, smsContent);
                    smsBody.setToId(flowRunPrcs1.getOpaddUser());
                }
                smsService.saveSms(smsBody, flowRunPrcs1.getOpaddUser(), "1", "1", title, context, "xoa1001");//存储事物提醒并推送消息
            }
            // 更新flowAssign
            try {
                List<FlowAssignWithBLOBs> assign = flowAssignMapper.getAssign(runId, prcsId, flowPrcs, users.getUserId());
                if (null != assign) {
                    for (FlowAssignWithBLOBs assign1 : assign) {
                        flowAssignMapper.updateStatus(assign1.getAssignId());
                    }
                }
            } catch (Exception e) {

            }
            /**     lr 工作流使用添加日志 ----办理完毕**/
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
            //装配日志对象
            flowRunLog.setType(Constant.TYPE19);
            flowRunLog.setRunId(runId);
            flowRunLog.setFlowPrcs(frp.getFlowPrcs());
            flowRunLog.setPrcsId(prcsId);
            //添加日志
            wfeLog.addFlowRunLog(flowRunLog);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg("false");
        }
        //}
        return ajaxJson;
    }


    //去重
    public List<Users> reAllUser(List<Users> list) {
        Map<Integer, Users> map = new HashMap<Integer, Users>();
        for (Users users : list) {
            map.put(users.getUid(), users);
        }
        list = new ArrayList<Users>(map.values());
        return list;
    }

    public ToJson<FlowFast> reQuery(FlowProcess flowProcess, String id, Users users, String flowPrcs, Integer flowId) {
        ToJson<FlowFast> tj = new ToJson<FlowFast>();
        FlowFast flowFast = new FlowFast();
        FlowRun flowRun = wfeFlowRun.find(Integer.parseInt(id));
        Integer runId = flowRun.getRunId();
        FlowRunPrcs flowRunPrcs1 = wfeFlowRunPrcs.getLastPrcsByRunId(runId);
        Users u = usersService.getUsersByuserId(flowRun.getBeginUser());
        flowRun.setUserName(u.getUserName());
        flowFast.setFlowRun(flowRun);
        flowFast.setFlowRunPrcs(flowRunPrcs1);
        //强制合并
        if ("1".equals(flowProcess.getGatherNode())) {
            //Integer gatherNodePriv = this.reGatherNodePriv(String.valueOf(flowFast.getFlowRun().getRunId()), Integer.parseInt(flowPrcs), users.getUserId(), flowId);
            Integer gatherNodePriv = workServiceImpl.findFlowPrcsProcess(String.valueOf(flowFast.getFlowRun().getRunId()), Integer.parseInt(flowPrcs), users.getUserId(), flowId, flowProcess.getPrcsId());
            flowFast.setGatherNodePriv(String.valueOf(gatherNodePriv));
        } else {
            flowFast.setGatherNodePriv(flowProcess.getGatherNode());
        }
        tj.setObject(flowFast);
        tj.setMsg("只显示查询！");
        tj.setFlag(0);
        return tj;
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：根据传入的runId和userId来检测此用户和流程是否有委托规则，如果有，返回被委托人userId
     * @创建时间：10:23 2018/7/24
     **/
    public String getUserId(String runId, String userId) {
        //根据flowId和userId查出FlowRule对象
        List<FlowRule> flowRuleList = flowRuleMapper.getFlowRuleList(runId, userId);
        if (flowRuleList.size() != 0) {
            //为了兼容老版本，可能有相同的委托规则
            FlowRule flowRule = flowRuleList.get(0);
            //查询出来的对象不能为空
            if (flowRule != null) {
                //判断状态是不是“1”开启状态
                if (flowRule.getStatus().equals("1")) {
                    //判断是不是一直有效（也就是时间为null）
                    if (flowRule.getBeginDate() == null && flowRule.getEndDate() == null) {
                        return flowRule.getToId();
                    } else {
                        try {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            //当前系统时间
                            Date atDate = new Date();
                            //开始时间
                            Date beginDate = sdf.parse(flowRule.getBeginDate());

                            //结束时间
                            Date endDate = sdf.parse(flowRule.getEndDate());

                            if (atDate.before(endDate) && atDate.after(beginDate)) {
                                return flowRule.getToId();
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 用map存取所有流程步骤信息附加userId
     * 王禹萌
     * 2018-07-24 16：44
     */

    public Map<String, FlowProcess> queryFlowProcessUserId(Integer flowId, Integer runId) {
        //获取所有的流程步骤
        List<FlowProcess> allFp = wfeFlowProcess.findRunIdFlowId(flowId, runId);
        Map<String, FlowProcess> map = new HashMap<String, FlowProcess>();
        //根据对应条件遍历流程步骤过滤
        for (int i = 0; i < allFp.size(); i++) {
            FlowProcess flowProcess = allFp.get(i);
            map.put(String.valueOf(flowProcess.getId()), flowProcess);
        }
        return map;
    }

    public AjaxJson editWorkfrom(String flowId, String formdata, Integer runId,
                                 String runName, String sqlType, Users users) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<String, Object>();
        //文号修改
        map.put("runId", runId);
        map.put("runName", runName);
        wfeFlowRun.updateState(map);
        //解决异常输入'
        formdata = formdata.replace("'", "");
        //用来存储sql传入参数
        Map<String, Object> param = new HashMap();
        //JSONArray json = new JSONArray();
        String tableName = "flow_data_" + flowId;
        //表单上所有的数据
        List<Map<String, Object>> l = JSONArray.parseObject(formdata, List.class);
        //用来存储表单上所有的数据
        List<Map<String, Object>> lAll = new ArrayList<Map<String, Object>>();
        //处理异常数据,前台传入参数可能为空
        for (int i = 0; i < l.size(); i++) {
            if (l.get(i).size() == 2 && (String) l.get(i).get("key") != "") {
                lAll.add(l.get(i));
            }
        }
        //此段代码只为添加对前端传入参数的异常处理
        List<String> keyc = new ArrayList<String>();
        for (Map<String, Object> m : l) {
            if (keyc.contains(m.get("key"))) {
                ajaxJson.setMsg("There are duplicate fields in the form parameter!" + map.get("key"));
                ajaxJson.setFlag(true);
                return ajaxJson;
            }
            keyc.add((String) map.get("key"));
        }
        List<Map<String, Object>> mAll = new ArrayList<Map<String, Object>>();

        //StringBuffer sbcreate = new StringBuffer();
        try {
            //获取该表数据库中的所有的列
            List<String> columns = this.createTable(tableName, sqlType, lAll);
            if (columns.size() > 0) {
                //用于存储数据库插入的字段
                List<String> key = new ArrayList<String>();
                //用于存储新增字段
                List<String> unusual = new ArrayList<String>();
                //用于获取传入表单上的所有key值
                List<String> Allkey = new ArrayList<String>();
                //用于存储已删除字段
                List<String> delkey = new ArrayList<String>();
                //遍历表单数据获取新增字段和所有
                for (Map<String, Object> m : lAll) {
                    String keyBd = (String) m.get("key");
                    if (!columns.contains(keyBd.toUpperCase())) {
                        if (!StringUtils.checkNull((String) m.get("key"))) {
                            //添加新增的表字段
                            unusual.add((String) m.get("key"));
                        }
                    }
                    //获取所有表单传入键值
                    Allkey.add((String) m.get("key"));
                }
                //移除数据库中非DATA开头的数据
                Iterator<String> it = columns.iterator();
                while (it.hasNext()) {
                    String x = it.next();
                    if (!x.toUpperCase().contains("DATA")) {
                        it.remove();
                    }
                }
                //存储表单可能删除的列
                for (int i = 0; i < columns.size(); i++) {
                    if (!Allkey.contains(columns.get(i))) {
                        delkey.add(columns.get(i));
                    }
                }
                //添加表的列
                if (unusual.size() > 0) {
                    param.put("tableName", tableName);
                    param.put("keys", unusual);
                    workMapper.addcolumn(param);
                }

                Map<String, Object> maps = new HashMap<String, Object>();
                maps.put("tableName", tableName);
                maps.put("runId", runId);
                //查询该表单的信息
                Map<String, Object> m = workMapper.select(maps);
                key = new ArrayList<String>();
                List<Object> value = new ArrayList<Object>();
                if (m == null || m.size() == 0) {
                    key.add("RUN_ID");
                    value.add(String.valueOf(runId));
                    key.add("RUN_NAME");
                    value.add(runName);
                    key.add("BEGIN_TIME");
                    String beginTime = DateFormat.getDatestrTime(new Date());
                    value.add(beginTime);
                    key.add("BEGIN_USER");
                    String beginUser = users.getUserId();
                    value.add(beginUser);
                    key.add("FLOW_AUTO_NUM");
                    value.add(0);
                    key.add("FLOW_AUTO_NUM_YEAR");
                    value.add(0);
                    key.add("FLOW_AUTO_NUM_MONTH");
                    value.add(0);


                    for (Map<String, Object> map1 : lAll) {
                        key.add((String) map1.get("key"));
                        value.add((String) map1.get("value"));
                    }

                    //表单可能删除的列
                    for (String s : delkey) {
                        key.add(s);
                        value.add("");
                    }
                    param.put("tableName", tableName);
                    param.put("keys", key);
                    param.put("values", value);
                    workMapper.insert(param);
                } else {
                    if (lAll.size() != 0) {
                        for (Map<String, Object> map2 : lAll) {
                            key.add((String) map2.get("key") + "=" + "'" + (String) map2.get("value") + "'");

                        }
                        param.put("tableName", tableName);
                        param.put("keys", key);
                        param.put("runId", String.valueOf(runId));
                        workMapper.update(param);
                    }
                }
            }
            ajaxJson.setMsg("OK");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            L.e("work editWorkfrom:" + e);
        }
        return ajaxJson;

    }

    //新建一个子流程
    private Integer newFlowRun(FlowProcess flowProcess, String runId, String userId) {
        if (flowProcess != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse");
            if (StringUtils.checkNull((String) request.getSession().getAttribute(
                    "loginDateSouse"))) {
                sqlType = "xoa1001";
            }


            //添加子流程所需  用户信息 部门信息
            // Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
            // Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
            Users users = usersMapper.getUsersByuserId(userId);
            Department department = departmentService.getDeptById(users.getDeptId());
            //判断是否为有子流程并开启了子流程
            if (flowProcess.getPrcsType() == 1 && flowProcess.getChildFlow() != 0) {
                FlowRun sonFlowRun = null;
                Integer flowRunId = null;
                FlowSort flowSort = flowSortMapper.getFlowSortByFlowId(flowProcess.getChildFlow());//判断为  什么类型流程
                FileUploadUtil fileUploadUtil = new FileUploadUtil();
                if ("DOCUMENTTYPE".equals(flowSort.getSortMainType())) {//这是公文新建子流程
                    //获取父公文实体类
                    DocumentModel fathDocument = documentSerivce.checkRunId(Integer.parseInt(runId));
                    List<Attachment> fathAttach = new ArrayList<Attachment>();//先设置空的正文
                    //获取父公文的正文
                    if (StringUtils.checkNull(fathDocument.getMainAipFile())) {//判断api为空
                        fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainFileName(), fathDocument.getMainFile(), sqlType, "document");
                    } else {
                        fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainAipFileName(), fathDocument.getMainAipFile(), sqlType, "document");
                    }
                    //复制文件
                    List<Attachment> sonAttach = fileUploadUtil.cppyFile(fathAttach, sqlType, "document");
                    for (Attachment attachment : sonAttach) {
                        enclosureService.saveAttachment(attachment);
                    }
                    Object[] o = FileUploadUtil.reAttachment(sonAttach);
                    DocumentModelWithBLOBs document = new DocumentModelWithBLOBs();
                    if (StringUtils.checkNull(fathDocument.getMainAipFile())) {//pdf为空  复制word
                        document.setMainFile(o[0].toString().split(",")[0]);
                        document.setMainFileName(o[1].toString().split("\\*")[0]);
                    } else {
                        document.setMainAipFile(o[0].toString().split(",")[0]);
                        document.setMainAipFileName(o[1].toString().split("\\*")[0]);
                    }

                    document.setCreater(userId);
                    //document.setTitle(fathDocument.getTitle());
                    if ("SENDNG".equals(flowSort.getSortDetailType())) {
                        document.setDocumentType("0");
                    } else if ("RECEIVE".equals(flowSort.getSortDetailType())) {
                        document.setDocumentType("1");
                    }

                    ToJson<Object> result = documentSerivce.saveDocument(users, flowProcess.getChildFlow(), 1, "1", "", document, request);
                    document = (DocumentModelWithBLOBs) result.getObject();
                    flowRunId = document.getRunId();
                    FlowRun son = wfeFlowRun.find(flowRunId);
                    sonFlowRun = son;
                } else {
                    //ToJson<FlowFast> fastAdd = workFastAdd(users, flowProcess.getChildFlow(), 1, "1", "", request, null, null, "0");
                    //FlowFast flowFast = (FlowFast) fastAdd.getObject();
                    Integer childFlow = flowProcess.getChildFlow();//子流程id
                    FlowTypeModel flowType = flowTypeModelMapper.queryOneObject(childFlow);//查看当前流程信息
                    //自动文号表达式
                    String autoName = flowType.getAutoName();
                    String beginTime = DateFormat.getStrDate(new Date());
                    //创建子流程流程实例

                    FlowRun flowRun = this.getRun(autoName, childFlow, users, beginTime, flowType, department, null);
                    sonFlowRun = flowRun;
                    //子流程runId
                    flowRunId = flowRun.getRunId();


                    //创建子流程第一步
                    FlowRunPrcs flowRunPrcs = new FlowRunPrcs(flowRunId, 1, users.getUserId(), null, "0000-00-00 00:00:00", "1", 1, "1", "0", beginTime, "0000-00-00 00:00:00", users.getDeptId(), "0", "0");
                    wfeFlowRunPrcs.save(flowRunPrcs);
                    //lr 添加在新建时就创建表单
                    //添加表单
                    FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowRun.getFlowId());
                    //表单
                    FlowFormType flowFormType = flowFormTypeMapper.qureyItemMax(flowTypeModel.getFormId());
                    //解析表单
                    Document document = getField(flowFormType.getPrintModel());
                    List<String> dataList = HtmlUtil.getAllData(document);
                    if (dataList != null) {
                        List<Map<String, Object>> mapList = new ArrayList<>();
                        for (int i = 0; i < dataList.size(); i++) {//表单信息
                            Map<String, Object> map = new HashMap<>();
                            map.put("key", dataList.get(i));
                            mapList.add(map);
                        }
                        if (mapList.size() > 0) {//去相关的流程  添加信息
                            String tableName = "flow_data_" + flowRun.getFlowId();
                            List<String> flowDataList = this.createTable(tableName, sqlType, mapList);
                            if (flowDataList != null && flowDataList.size() > 0) {//当前表的字段
                                Map<String, Object> maps = new HashMap<String, Object>();
                                maps.put("tableName", tableName);
                                maps.put("runId", flowRunId);
                                //查询该表单的信息
                                Map<String, Object> m = workMapper.select(maps);
                                Map<String, Object> inserDataMap = new HashMap<>();
                                List<String> key = new ArrayList<String>();
                                List<String> value = new ArrayList();
                                if (m == null || m.size() == 0) {
                                    for (int i = 0; i < flowDataList.size(); i++) {//去匹配数据
                                        String keyStr = flowDataList.get(i);
                                        if (!keyStr.equals("ID") && !keyStr.equals("FLOW_AUTO_NUM") && !keyStr.equals("FLOW_AUTO_NUM_YEAR") && !keyStr.equals("FLOW_AUTO_NUM_MONTH")) {
                                            if (keyStr.equals("BEGIN_TIME")) {
                                                key.add(keyStr);
                                                value.add(DateFormat.getDatestr(new Date()));
                                            } else if (keyStr.equals("RUN_ID")) {
                                                key.add(keyStr);
                                                value.add(flowRunId + "");
                                            } else if (keyStr.equals("BEGIN_USER")) {
                                                key.add(keyStr);
                                                value.add(userId);
                                            } else if (keyStr.equals("RUN_NAME")) {
                                                key.add(keyStr);
                                                value.add(flowRun.getRunName());
                                            } else {
                                                key.add(keyStr);
                                                value.add("");
                                            }
                                        }

                                    }
                                    inserDataMap.put("tableName", tableName);
                                    inserDataMap.put("keys", key);
                                    inserDataMap.put("values", value);
                                    workMapper.insert(inserDataMap);
                                    //将最新表单data值与flow_data表中的列对比，没有的列则添加
                                    Map<String, Object> param = new HashMap();
                                    dataList.removeAll(flowDataList);
                                    param.put("tableName", tableName);
                                    param.put("keys", dataList);
                                    workMapper.addcolumn(param);
                                }
                            }
                        }
                    }
                }
                //父流程
                FlowRun parent = wfeFlowRun.find(Integer.parseInt(runId));

                //先判断是否转交公文正文
                List<FlowProcess> flowProcesses = flowProcessMapper.selectRelationIn(runId);//判断父流程是否转交公文正文
                String str = "";
                String str2 = "";
                String str3 = "";


                for (FlowProcess flow1 : flowProcesses) {
                    int result1 = flow1.getRelationIn().indexOf("公文正文=>公文正文");
                    int result2 = flow1.getRelationIn().indexOf("公文正文=>流程附件");
                    int result3 = flow1.getRelationIn().indexOf("流程附件=>流程附件");
                    if (-1 != result1) {
                        str = "公文正文";
                    }
                    if (-1 != result2) {
                        str2 = "公文正文到流程附件";
                    }
                    if (-1 != result3) {
                        str3 = "附件到附件";
                    }


                }
                List<Attachment> fathAttach = new ArrayList<Attachment>();//先设置空的正文
                //获取流程的附件
                if (!"公文正文".equals(str)) {
                    DocumentMapper.updateDocumentAttach(sonFlowRun.getRunId());//把公文正文设置为空
                }
                if ("公文正文到流程附件".equals(str2)) {//正文到付件和附件到附件
                    //获取父公文实体类
                    DocumentModel fathDocument = documentSerivce.checkRunId(Integer.parseInt(runId));
                    //获取父公文的正文
                    if (StringUtils.checkNull(fathDocument.getMainAipFile())) {//判断api为空
                        fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainFileName(), fathDocument.getMainFile(), sqlType, "document");
                    } else {
                        fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainAipFileName(), fathDocument.getMainAipFile(), sqlType, "document");
                    }
                    //复制文件
                    List<Attachment> sonAttach = fileUploadUtil.cppyFiles(fathAttach, sqlType, "document");
                    for (Attachment attachment : sonAttach) {
                        enclosureService.saveAttachment(attachment);
                    }
                    Object[] o = FileUploadUtil.reAttachment(sonAttach);//返回附件信息

                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("runId", flowRunId);
                    FlowRun son = wfeFlowRun.find(flowRunId);
                    sonFlowRun = son;
                    if (StringUtils.checkNull(son.getAttachmentId())) {   //子流程附件为空，进行父流程附件复制
                        if (!StringUtils.checkNull(parent.getAttachmentId())) {
                            if (!",".equals(parent.getAttachmentId().substring(parent.getAttachmentId().length() - 1, parent.getAttachmentId().length()))) {
                                parent.setAttachmentId(parent.getAttachmentId() + ",");
                            }
                        }
                        if ("".equals(str3)) {//不传父流程附件
                            parent.setAttachmentId("");
                        }
                        son.setAttachmentId(son.getAttachmentId() + parent.getAttachmentId());
                    } else {    //子流程不为空  进行父流程附件复制
                        if (!StringUtils.checkNull(parent.getAttachmentId())) {
                            if (!",".equals(parent.getAttachmentId().substring(parent.getAttachmentId().length() - 1, parent.getAttachmentId().length()))) {
                                parent.setAttachmentId(parent.getAttachmentId() + ",");
                            }
                        }
                        if ("".equals(str3)) {//不传父流程附件
                            parent.setAttachmentId("");
                        }
                        son.setAttachmentId(son.getAttachmentId() + parent.getAttachmentId());
                    }

                    if (StringUtils.checkNull(son.getAttachmentName())) {
                        if (!StringUtils.checkNull(parent.getAttachmentName())) {
                            if (!"*".equals(parent.getAttachmentName().substring(parent.getAttachmentName().length() - 1, parent.getAttachmentName().length()))) {
                                parent.setAttachmentName(parent.getAttachmentName() + "*");
                            }
                        }
                        if ("".equals(str3)) {//不传父流程附件
                            parent.setAttachmentName("");
                        }
                        son.setAttachmentName(son.getAttachmentName() + parent.getAttachmentName());
                    } else {//子流程不为空  进行父流程附件name复制
                        if (!StringUtils.checkNull(parent.getAttachmentId())) {
                            if (!",".equals(parent.getAttachmentId().substring(parent.getAttachmentId().length() - 1, parent.getAttachmentId().length()))) {
                                parent.setAttachmentId(parent.getAttachmentId() + ",");
                            }
                        }
                        if ("".equals(str3)) {
                            parent.setAttachmentName("");
                        }
                        son.setAttachmentName(son.getAttachmentName() + parent.getAttachmentName());
                    }

                    map.put("attachmentId", son.getAttachmentId() + o[0].toString());
                    map.put("attachmentName", son.getAttachmentName() + o[1].toString());
                    wfeFlowRun.updateAttachment(map);
                }

                if ("附件到附件".equals(str3) && "".equals(str2)) {//正文不到付件和附件到附件
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("runId", flowRunId);
                    FlowRun son = wfeFlowRun.find(flowRunId);
                    if (StringUtils.checkNull(son.getAttachmentId())) {//子流程附件为空，进行父流程附件复制
                        if (!StringUtils.checkNull(parent.getAttachmentId())) {
                            if (!",".equals(parent.getAttachmentId().substring(parent.getAttachmentId().length() - 1, parent.getAttachmentId().length()))) {
                                parent.setAttachmentId(parent.getAttachmentId() + ",");
                            }
                        }
                        if ("".equals(str3)) {//不传父流程附件
                            parent.setAttachmentId("");
                        }
                        son.setAttachmentId(son.getAttachmentId() + parent.getAttachmentId());
                    } else {//子流程不为空  进行父流程附件复制
                        if (!StringUtils.checkNull(parent.getAttachmentId())) {
                            if (!",".equals(parent.getAttachmentId().substring(parent.getAttachmentId().length() - 1, parent.getAttachmentId().length()))) {
                                parent.setAttachmentId(parent.getAttachmentId() + ",");
                            }
                        }
                        if ("".equals(str3)) {//不传父流程附件
                            parent.setAttachmentId("");
                        }
                        son.setAttachmentId(son.getAttachmentId() + parent.getAttachmentId());
                    }

                    if (StringUtils.checkNull(son.getAttachmentName())) {
                        if (!StringUtils.checkNull(parent.getAttachmentName())) {
                            if (!"*".equals(parent.getAttachmentName().substring(parent.getAttachmentName().length() - 1, parent.getAttachmentName().length()))) {
                                parent.setAttachmentName(parent.getAttachmentName() + "*");
                            }
                        }
                        if ("".equals(str3)) {//不传父流程附件
                            parent.setAttachmentName("");
                        }
                        son.setAttachmentName(son.getAttachmentName() + parent.getAttachmentName());
                    } else {//子流程不为空  进行父流程附件name复制
                        if (!StringUtils.checkNull(parent.getAttachmentId())) {
                            if (!",".equals(parent.getAttachmentId().substring(parent.getAttachmentId().length() - 1, parent.getAttachmentId().length()))) {
                                parent.setAttachmentId(parent.getAttachmentId() + ",");
                            }
                        }
                        if ("".equals(str3)) {
                            parent.setAttachmentName("");
                        }
                        son.setAttachmentName(son.getAttachmentName() + parent.getAttachmentName());
                    }

                    map.put("attachmentId", son.getAttachmentId());
                    map.put("attachmentName", son.getAttachmentName());
                    wfeFlowRun.updateAttachment(map);
                }


                FlowRun flowRun = flowRunMapper.find(flowRunId);
                DocumentModel documentModel = documentSerivce.checkRunId(flowRunId);
                FlowRunPrcs flowRunPrcs = flowRunPrcsMapper.queryByRunId(flowRunId);
                FlowProcess process = flowProcessMapper.findProcess(flowRun.getFlowId(), 1);
                boolean bol = false;
                SysPara myproject = sysParaMapper.querySysPara("MYPROJECT");
                if (myproject != null && !StringUtils.checkNull(myproject.getParaValue())
                        && "dazu".equals(myproject.getParaValue())) {
                    bol = true;
                }
                String title = bol ? parent.getRunName() : "您有新的工作需要办理";
                String context = "流水号：" + flowRunId + "，工作名称/文号：" + parent.getRunName();
                String smsContent = "流水号：" + flowRunId + "，工作名称/文号：" + parent.getRunName();
                if ("DOCUMENTTYPE".equals(flowSort.getSortMainType())) {
                    String remindUrl = "/workflow/work/workform?opflag=" + Integer.parseInt(flowRunPrcs.getOpFlag()) + "&flowId=" + flowRun.getFlowId() + "&flowStep=1" + "&tableName=document&tabId=" + documentModel.getId() + "&runId=" + flowRunId + "&prcsId=1" + "&isNomalType=false";
                    SmsBody smsBody = new SmsBody(users.getUserId(), "70", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
                    smsService.saveSms(smsBody, userId, "1", "1", title, context, sqlType);//存储事物
                } else {
                    String remindUrl = "/workflow/work/workform?opflag=" + Integer.parseInt(flowRunPrcs.getOpFlag()) + "&flowId=" + flowRun.getFlowId() + "&flowStep=1&runId=" + flowRunId + "&prcsId=1";
                    SmsBody smsBody = new SmsBody(users.getUserId(), "7", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
                    smsService.saveSms(smsBody, userId, "1", "1", title, context, sqlType);//存储事物
                }
                //子流程添加当前流程为父流程
                FlowRun flowRun1 = new FlowRun();
                flowRun1.setRunId(flowRunId);
                flowRun1.setParentRun(Integer.parseInt(runId));
                flowRun1.setParentRunName(parent.getRunName());
                flowRunMapper.updateParentRUN(flowRun1);

                workFlowCreateController.saveFlowAutoNum(sonFlowRun.getFlowId(), sonFlowRun.getRunId(), sonFlowRun.getRunName(),
                        sonFlowRun.getBeginTime(), request);
                try {
                    //添加映射字段
                    mapping(parent, sonFlowRun, 0, flowProcess);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return flowRunId;
            }
        }
        return null;
    }

    //结束流程

    /**
     * @创建作者:李然 Lr
     * @方法描述：解析表单数据
     * @创建时间：10:08 2018/8/20
     **/
    public Document getField(String printModel) {
        Document document = null;
        //解析html
        document = Jsoup.parse(printModel);
        return document;
    }

    private void overMotion(String runId) {
        FlowRun flowRun1 = wfeFlowRun.find(Integer.parseInt(runId));
        //父流程runId
        Integer parentRunId = flowRun1.getParentRun();
        FlowRun flowRun2 = wfeFlowRun.find(parentRunId);
        //父流程flowId
        Integer parentflowId = flowRun2.getFlowId();
        //父流程flowPrcs 通过父流程runid得到
        FlowRunPrcs flowRunPrcs = WFEFlowRunPrcsMapper.selectPrcsId(parentRunId);
        Integer parentFlowPrcs = flowRunPrcs.getFlowPrcs();

        FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(parentflowId, parentFlowPrcs);
        if (flowProcess != null) {
            if (flowProcess.getPrcsTo() != null && !flowProcess.getPrcsTo().equals("0")) {
                FlowRunPrcs fl = new FlowRunPrcs();
                fl.setId(flowRunPrcs.getId());
                fl.setRunId(flowRunPrcs.getRunId());
                fl.setPrcsId(flowRunPrcs.getPrcsId() + 1);
                fl.setTopFlag("0");
                fl.setRunId(parentRunId);
                fl.setPrcsFlag("1");
                fl.setFlowPrcs(Integer.parseInt(flowProcess.getPrcsTo()));
                //查看是否有委托规则
                fl.setCreateTime(DateFormat.getStrDate(new Date()));
                fl.setPrcsTime("0000-00-00 00:00:00");
                fl.setDeliverTime("0000-00-00 00:00:00");
                fl.setActiveTime("0000-00-00 00:00:00");
                fl.setParent(flowProcess.getPrcsId() + "");
                fl.setParentPrcsId(flowProcess.getPrcsId() + "");
                //获取主办人并添加
                String procesUserId = flowProcess.getAutoUserOpReturn();
                fl.setOpFlag("1");
                try {
                    String userId = getUserId(runId, procesUserId);
                    if (userId != null && userId != "") {
                        procesUserId = userId;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                fl.setUserId(procesUserId);
                wfeFlowRunPrcs.save(fl);

                //获取经办人并添加
                String jingban = flowProcess.getAutoUserReturn();
                List<String> jingbanList = new ArrayList<>();
                if (jingban != null && jingban.length() > 0) {
                    String[] jingbans = jingban.split(",");
                    for (int i = 0; i < jingbans.length; i++) {
                        String jingbanren = jingbans[i].trim();
                        if (!jingbanren.equals(procesUserId)) {
                            try {
                                String userId = getUserId(runId, jingbanren);
                                if (userId != null && userId != "") {
                                    jingbanren = userId;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            fl.setOpFlag("0");
                            fl.setUserId(jingbanren);
                            wfeFlowRunPrcs.save(fl);
                        }

                    }
                }
            }
        }
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：返回具体字段，data_xx
     * @创建时间：10:08 2018/8/20
     **/
    public String getCustomData(Document document, String str) {
        Elements elements = document.select("[title=" + str + "]");
        String name = null;

        if (elements.size() > 0) {
            for (int i = 0; i < elements.size(); i++) {
                name = elements.get(i).attr("name");
            }
        }
        return name;
    }

    public Integer getFormId(FlowRun flowRun1) {
        Integer formId = null;
        if (flowRun1 != null) {
            FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowRun1.getFlowId());
            if (flowTypeModel != null) {
                formId = flowTypeModel.getFormId();
            }
        }
        return formId;
    }

    //插入子流程表单映射数据
    public int insertSonDataValue(List<String> dataParentList, FlowRun flowRun1,
                                  String tableName, List<String> dataSonList, String tableNameSon, FlowRun flowRun) {
        //获得父流程的数据
        //dataList=workMapper.getDataValue(dataParentList,flowRun1.getRunId(),tableName);

        return 1;
    }

    public void assemble(String relationIn, Document documentParent, Document documentSon) {
        if (relationIn != null && !relationIn.equals("")) {
            //分割获取映射集合
            String[] relationInArrays = relationIn.split(",");
            //将汉字映射分割，分别存入父流程数据dataParentList和子流程dataSonList
            for (int i = 0; i < relationInArrays.length; i++) {
                String[] relationInArray = relationInArrays[i].split("=>");
                String dataParent = getCustomData(documentParent, relationInArray[0]);
                String dataSon = getCustomData(documentSon, relationInArray[1]);
                if (dataParent != null && dataSon != null) {
                    dataParentList.add(dataParent);
                    dataSonList.add(dataSon);
                }
            }
        }
    }

    public Map<String, Object> ParentSon(FlowRun flowRun) {
        if (flowRun != null && flowRun.getParentRun() != 0) {
            //查找父流程
            FlowRun parentFlowRun = flowRunMapper.find(flowRun.getParentRun());
            //获得父流程表单id
            Integer formIdParent = getFormId(parentFlowRun);
            //获得子流程表单id
            Integer formIdSon = getFormId(flowRun);
            //父流程表名
            String tableName = "flow_data_" + parentFlowRun.getFlowId();
            //子流程表名
            String tableNameSon = "flow_data_" + flowRun.getFlowId();

            if (formIdParent != null && formIdSon != null) {
                //获得父流程的表单实例
                FlowFormType flowFormTypeParent = flowFormTypeMapper.qureyItemMax(formIdParent);
                //获得子流程的表单实例
                FlowFormType flowFormTypeSon = flowFormTypeMapper.qureyItemMax(formIdSon);
                //获得具体的表单数据 父流程
                String printModelParent = flowFormTypeParent.getPrintModel();
                //获得具体的表单数据 子流程
                String printModelSon = flowFormTypeSon.getPrintModel();
                //解析表单 父流程
                Document documentParent = getField(printModelParent);
                //解析表单 子流程
                Document documentSon = getField(printModelSon);

                if (flowFormTypeParent != null) {
                    //获取父流程转发子流程那一步骤
                    Integer flowId = parentFlowRun.getFlowId();
                    Integer runId = parentFlowRun.getRunId();
                    FlowProcess flowProcess = wfeFlowProcessMapper.selectFlowProcessByRunId(parentFlowRun.getFlowId(), parentFlowRun.getRunId());
                    //获取父对子的映射
                    String relationIn = flowProcess.getRelationIn();
                    if (relationIn != null && !relationIn.equals("")) {
                        List<String> parentDataList = new ArrayList<>();
                        List<String> sonDataList = new ArrayList<>();
                        //取出每一组映射字段
                        String[] parentSons = relationIn.split(",");
                        for (int i = 0; i < parentSons.length; i++) {
                            //分割为父流程字段和子流程字段
                            String[] parentSon = parentSons[i].split("=>");
                            //父流程字段
                            String parent = parentSon[0];
                            //子流程字段
                            String son = parentSon[1];
                            //返回具体date字段
                            String parentData = getCustomData(documentParent, parent);
                            String sonData = getCustomData(documentSon, son);
                            parentDataList.add(parentData);
                            sonDataList.add(sonData);
                        }
                        //List<String> parentDataValue=workMapper.getDataValue(parentDataList,parentFlowRun.getRunId(),tableName);
                        Map<String, Object> parentDataValue = workMapper.getDataValue(parentDataList, parentFlowRun.getRunId(), tableName);
                        Map<String, Object> reMap = new HashMap<String, Object>();
                        if (parentDataValue != null) {
                            reMap = new HashMap<String, Object>();
                            for (int i = 0; i < sonDataList.size(); i++) {
                                reMap.put(sonDataList.get(i), parentDataValue.get(parentDataList.get(i)));
                            }
                            return reMap;
                        }
                    }
                }
            }
        }
        return null;
    }

    public void sonParent(FlowRun flowRun) {
        if (flowRun != null && flowRun.getParentRun() != 0) {
            //查找父流程
            FlowRun parentFlowRun = flowRunMapper.find(flowRun.getParentRun());
            //获得父流程表单id
            Integer formIdParent = getFormId(parentFlowRun);
            //获得子流程表单id
            Integer formIdSon = getFormId(flowRun);
            //父流程表名
            String tableName = "flow_data_" + parentFlowRun.getFlowId();
            //子流程表名
            String tableNameSon = "flow_data_" + flowRun.getFlowId();

            if (formIdParent != null && formIdSon != null) {
                //获得父流程的表单实例
                FlowFormType flowFormTypeParent = flowFormTypeMapper.qureyItemMax(formIdParent);
                //获得子流程的表单实例
                FlowFormType flowFormTypeSon = flowFormTypeMapper.qureyItemMax(formIdSon);
                //获得具体的表单数据 父流程
                String printModelParent = flowFormTypeParent.getPrintModel();
                //获得具体的表单数据 子流程
                String printModelSon = flowFormTypeSon.getPrintModel();
                //解析表单 父流程
                Document documentParent = getField(printModelParent);
                //解析表单 子流程
                Document documentSon = getField(printModelSon);

                //获取父流程转发子流程那一步骤
                Integer flowId = parentFlowRun.getFlowId();
                Integer runId = parentFlowRun.getRunId();
                FlowProcess flowProcess = wfeFlowProcessMapper.selectFlowProcessByRunId(parentFlowRun.getFlowId(), parentFlowRun.getRunId());
                //获取子对父的映射
                String relationOut = flowProcess.getRelationOut();
                if (relationOut != null && !relationOut.equals("")) {
                    List<String> sonDataList = new ArrayList<>();
                    List<String> parentDataList = new ArrayList<>();
                    //取出每一组映射字段
                    String[] sonParents = relationOut.split(",");
                    for (int i = 0; i < sonParents.length; i++) {
                        //分割为子流程字段和父流程字段
                        String[] parentSon = sonParents[i].split("=>");
                        //子流程字段
                        String son = parentSon[0];
                        //父流程字段
                        String parent = parentSon[1];
                        //返回具体date字段
                        String parentData = getCustomData(documentParent, parent);
                        String sonData = getCustomData(documentSon, son);
                        parentDataList.add(parentData);
                        sonDataList.add(sonData);
                    }
                    if (sonDataList != null && sonDataList.size() > 0) {
                        Map<String, Object> sonDataValue = workMapper.getDataValue(sonDataList, flowRun.getRunId(), tableNameSon);
                        StringBuffer sb = new StringBuffer();
                        String setSql = null;
                        if (sonDataValue != null && sonDataValue.size() > 0) {
                            for (int i = 0; i < parentDataList.size(); i++) {
                                sb.append(parentDataList.get(i) + "=" + "'" + sonDataValue.get(sonDataList.get(i)) + "'" + ",");
                            }
                         /*   for (int i = 0; i < sonDataValue.size(); i++) {
                                sb.append(parentDataList.get(i) + "=" + "'" + sonDataValue.get(i) + "'" + ",");
                            }*/
                            if (sb.charAt(sb.length() - 1) == ',') {
                                setSql = sb.substring(0, sb.length() - 1);
                            }
                            if (setSql != null) {
                                workMapper.updateDataValue(setSql, tableName, parentFlowRun.getRunId());
                            }
                        }
                    }
                }

            }
        }
    }


    public AjaxJson findFinalfeedback(Integer runId) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            List<FlowRunFeedback> list = flowRunFeedbackMapper.findFinalfeedback(runId);
            ajaxJson.setObj(list);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }

    public String getBranchCount(List<FlowRunPrcs> flowRunPrcs, String branchCount, String flowPrcs) {
        for (FlowRunPrcs flowRunPrcs1 : flowRunPrcs) {
            if (!StringUtils.checkNull(flowRunPrcs1.getBranchCount())) {
                branchCount += flowRunPrcs1.getBranchCount() + ",";
            }
        }
        if (!StringUtils.checkNull(branchCount)) {
            branchCount = branchCount + flowPrcs;
            String[] arrBranch = branchCount.split(",");
            Set<String> set = new HashSet<>();
            for (int i = 0, len = arrBranch.length; i < len; i++) {
                set.add(arrBranch[i]);
            }
            StringBuffer sb = new StringBuffer();
            String[] arrayResult = (String[]) set.toArray(new String[set.size()]);
            for (int i = 0, size = arrayResult.length; i < size; i++) {
                if (!StringUtils.checkNull(arrayResult[i]) && !"0".equals(arrayResult[i])) {
                    if (i < size - 1) {
                        sb.append(arrayResult[i]).append(",");
                    } else {
                        sb.append(arrayResult[i]);
                    }
                }
            }
            branchCount = sb.toString();
        }
        return branchCount;
    }

    public TriggerPlugIn getTrigger(String runId, String flowId, String sqlType, String beginUser, String beginTime, String runName, String flowPrcs, String prcsId, String currentPrcsId,
                                    String tabId, HttpServletRequest request, int turn) {
        //此map用来传递参数
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tableName", "flow_data_" + flowId);
        param.put("runId", runId);
        //查询存储存入数据库中信息
        Map<String, Object> flowDatas = workMapper.select(param);
        //此处代码可修改流程触发器解析表单的代码直接传入map省去此步骤
        String flowDataString = CollectionUtils.mapToString(flowDatas);

        if (StringUtils.checkNull(sqlType)) {
            param.put("tableSchema", "xoa1001");
        } else {
            param.put("tableSchema", sqlType);
        }
        //存储表单上映射
        Map<String, Object> mapForm = new HashMap<String, Object>();
        List<FlowFormType> allFlowForm = wfeFormTypeMapper.getFrombyFlowId(Integer.parseInt(flowId));
        FlowFormType flowFormType = allFlowForm.get(0);
        //获取表单信息
        Document document = HtmlUtil.getDom(flowFormType.getPrintModel());
        //获取该表所有的列
        List<String> columns = workMapper.showColumns(param);
        for (int i = 0, size = columns.size(); i < size; i++) {
            String name = HtmlUtil.getDocumentTitle(document, columns.get(i));
            String data = HtmlUtil.getDocumentName(document, name);
            mapForm.put(name, data);
        }
        //表单数据
        String fromString = JSON.toJSONString(mapForm);
        //插件类
        TriggerPlugIn triggerPlugIn = new TriggerPlugIn();
        triggerPlugIn.setFlowId(flowId);
        triggerPlugIn.setFormmat("2");//超链接格式//适用公告
        triggerPlugIn.setFromId(beginUser);
        triggerPlugIn.setSendTime(DateFormat.getDate(beginTime));
        triggerPlugIn.setSubject(runName);
        String url = request.getScheme() + "://" + request.getServerName() + ":" +
                request.getServerPort() + "/workflow/work/workformPreView?flowId=" + Integer.valueOf(flowId) + "&flowStep=" + Integer.valueOf(prcsId) + "&runId=" + runId + "";
        triggerPlugIn.setContent("<a href=" + url + ">" + url + "</a>");
        triggerPlugIn.setToId2("");
        triggerPlugIn.setFlowPrcs(flowPrcs);
        triggerPlugIn.setPrcsId(prcsId);
        triggerPlugIn.setModify(flowDataString);
        triggerPlugIn.setReject(fromString);
        triggerPlugIn.setTableName(runName);
        triggerPlugIn.setRunId(runId + "");
        triggerPlugIn.setRunName(runName);
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        triggerPlugIn.setUsers(user);
        triggerPlugIn.setFlag(this.returnMap().get(turn));
        triggerPlugIn.setRequest(request);
        triggerPlugIn.setSqlType(sqlType);
        triggerPlugIn.setTabId(tabId);
        triggerPlugIn.setCurrentPrcsId(currentPrcsId);
        return triggerPlugIn;
    }

    //流程过滤选人
    public List<Integer> getFilterlist(Integer userFilter, Users users, FlowProcess flowProcess) {
        List<Integer> userFilterlist = new ArrayList<Integer>();
        //当前用户部门
        Department department = departmentService.getDeptById(users.getDeptId());
        Department dparent = null;
        List<Department> list = null;
        switch (userFilter) {
            case 1://只允许本部门
                userFilterlist = usersService.getUidByConditions(users.getDeptId().toString(), 5);
                return userFilterlist;
            case 2://只允许本角色
                userFilterlist = usersService.getUidByConditions(String.valueOf(users.getUserPriv()), 6);
                return userFilterlist;
            case 3://只允许选择上级部门
                if (department.getDeptParent() == 0) {
                } else {
                    dparent = departmentService.getDeptById(department.getDeptParent());
                    userFilterlist = usersService.getUidByConditions(dparent.getDeptId().toString(), 5);
                }
                return userFilterlist;
            case 4://只允许选择下级部门
                list = departmentService.getChDept(users.getDeptId());
                if (list != null && list.size() > 0) {
                    StringBuffer stringBuffer = new StringBuffer();
                    for (Department department1 : list) {
                        stringBuffer.append(department1.getDeptId()).append(",");
                    }
                    userFilterlist = usersService.getUidByConditions(stringBuffer.toString(), 5);
                }
                return userFilterlist;
            case 5://同级部门
                if (department.getDeptParent() == 0) {
                    list = departmentService.getDepartmentByParet();
                } else {
                    dparent = departmentService.getDeptById(department.getDeptParent());
                    list = departmentService.getChDept(dparent.getDeptId());
                }
                if (list != null && list.size() > 0) {
                    StringBuffer stringBuffer = new StringBuffer();
                    for (Department department1 : list) {
                        stringBuffer.append(department1.getDeptId()).append(",");
                    }
                    userFilterlist = usersService.getUidByConditions(stringBuffer.toString(), 5);
                }
                return userFilterlist;
            case 6://指定部门
                if (!StringUtils.checkNull(flowProcess.getUserFilterPrcsDept())) {
                    userFilterlist = usersService.getUidByConditions(flowProcess.getUserFilterPrcsDept(), 5);
                }
                return userFilterlist;
            case 7://指定角色
                if (!StringUtils.checkNull(flowProcess.getUserFilterPrcsPriv())) {
                    userFilterlist = usersService.getUidByConditions(flowProcess.getUserFilterPrcsPriv(), 6);
                }
                return userFilterlist;
            case 8://本辅助部门
                if (!StringUtils.checkNull(users.getDeptIdOther())) {
                    userFilterlist = usersService.getUidByConditions(users.getDeptIdOther(), 3);
                }
                return userFilterlist;
            case 9://指定辅助部门
                if (!StringUtils.checkNull(flowProcess.getUserFilterPrcsDeptOther())) {
                    userFilterlist = usersService.getUidByConditions(flowProcess.getUserFilterPrcsDeptOther(), 3);
                }
                return userFilterlist;
            case 10://本辅助角色
                if (!StringUtils.checkNull(users.getUserPrivOther()))
                    userFilterlist = usersService.getUidByConditions(users.getUserPrivOther(), 4);
                return userFilterlist;
            case 11://指定辅助角色经办人
                if (!StringUtils.checkNull(flowProcess.getUserFilterPrcsPrivOther()))
                    userFilterlist = usersService.getUidByConditions(flowProcess.getUserFilterPrcsPrivOther(), 4);
                return userFilterlist;
            case 12://本部门和下级部门
                userFilterlist = usersService.getUidByConditions(users.getDeptId().toString(), 5);
                list = departmentService.getChDept(users.getDeptId());
                List<Integer> nextDep = new ArrayList<Integer>();
                if (list != null && list.size() > 0) {
                    StringBuffer stringBuffer = new StringBuffer();
                    for (Department department1 : list) {
                        stringBuffer.append(department1.getDeptId()).append(",");
                    }
                    nextDep = usersService.getUidByConditions(stringBuffer.toString(), 5);
                }
                userFilterlist.addAll(nextDep);
                return userFilterlist;
            default:
                return userFilterlist;
        }
    }

    public List<Users> getAutoTypelist(Department dep, Users users, String runId, FlowProcess flowProcess, List<FlowRunPrcs> allfrp) {
        List<Users> autoTypelist = new ArrayList<Users>();
        //部门针对对象步骤id
        Integer autoBaseUser = flowProcess.getAutoBaseUser();
        Department department = null;
        Department dparent = null;
        List<Users> list = null;
        Integer autoType = StringUtils.checkNull(flowProcess.getAutoType()) ? 0 : Integer.parseInt(flowProcess.getAutoType());
        switch (autoType) {
            case 0:
                return autoTypelist;
            case 1://自动选择流程发起人
                FlowRun flowRun = wfeFlowRun.find(Integer.parseInt(runId));
                autoTypelist = usersService.getUserByuserId(flowRun.getBeginUser());
                break;
            case 2://自动选择本部门主管
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        department = departmentService.getDeptById(users.getDeptId());
                        if (department != null) {
                            if (!StringUtils.checkNull(department.getManager())) {
                                autoTypelist = usersService.getUserByuserId(department.getManager());
                            }
                        }
                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users users1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getDeptById(users1.getDeptId());
                            autoTypelist = usersService.getUserByuserId(department.getManager());
                        }
                    }
                }
                break;
            case 3://自动选择默认人员
                //默认主办人
               /* Users usersOp = null;
                if (!StringUtils.checkNull(flowProcess.getAutoUserOp())){
                    usersOp = usersService.findUsersByuserId(flowProcess.getAutoUserOp());
                    usersOp.setOpFlag("1");
                }
*/
                //默认经办人
                List<Users> usersList = usersService.getUserByuserId(flowProcess.getAutoUser());
                Iterator<Users> iterator = usersList.iterator();
                while (iterator.hasNext()) {
                    Users users1 = iterator.next();
                    if (!StringUtils.checkNull(flowProcess.getAutoUserOp())) {
                        if (users1.getUserId().equals(flowProcess.getAutoUserOp())) {
                            users1.setOpFlag("1");
                            break;
                        }
                    } else {
                        users1.setOpFlag("1");
                        break;
                    }
                }
                autoTypelist.addAll(usersList);
                break;
            case 4://自动选择上级主管领导
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        department = departmentService.getDeptById(users.getDeptId());
                        // dparent = departmentService.getDeptById(department.getDeptParent());
                        if (department != null) {
                            if (!StringUtils.checkNull(department.getLeader1())) {
                                autoTypelist = usersService.getUserByuserId(department.getLeader1());
                            }
                        }
                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users users1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getDeptById(users1.getDeptId());
                            // dparent = departmentService.getDeptById(department.getDeptParent());
                            if (department != null) {
                                if (!StringUtils.checkNull(department.getLeader1())) {
                                    autoTypelist = usersService.getUserByuserId(department.getLeader1());
                                }
                            }
                        }
                    }
                }
                break;
            case 5://自动选择一级部门主管
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        department = departmentService.getFatherDept(users.getDeptId());
                        if (department != null) {
                            if (!StringUtils.checkNull(department.getManager())) {
                                autoTypelist = usersService.getUserByuserId(department.getManager());
                            }
                        }

                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users users1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getFatherDept(users1.getDeptId());
                            if (department != null) {
                                if (!StringUtils.checkNull(department.getManager())) {
                                    autoTypelist = usersService.getUserByuserId(department.getManager());
                                }
                            }
                        }
                    }
                }
                break;
            case 6://自动选择上级分管主管
                for (FlowRunPrcs flowRunPrcs : allfrp) {
                    //0代表当前步骤
                    if (autoBaseUser == 0) {
                        //department = departmentService.getFatherDept(users1.getDeptId());
                        dparent = departmentService.getDeptById(users.getDeptId());
                        if (dparent != null) {
                            autoTypelist = usersService.getUserByuserId(dparent.getLeader2());
                        }
                    } else {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users users1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            //department = departmentService.getFatherDept(users1.getDeptId());
                            dparent = departmentService.getDeptById(users1.getDeptId());
                            if (dparent != null) {
                                autoTypelist = usersService.getUserByuserId(dparent.getLeader2());
                            }
                        }
                    }
                }
                break;
            case 7://按表单字段选择
                String autoUser = flowProcess.getAutoUser();
                String a[] = autoUser.split(",");
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("tableName", "flow_data_" + flowProcess.getFlowId());
                map.put("runId", runId);
                Map<String, Object> maps = workMapper.select(map);
                Users aUser = null;
                if (maps != null) {
                    String userName = (String) maps.get("DATA_" + a[0]) == null ? (String) maps.get("data_" + a[0]) : (String) maps.get("DATA_" + a[0]);
                    if (StringUtils.checkNull(userName)) {
                        userName = (String) maps.get(a[0].toLowerCase()) == null ? (String) maps.get(a[0].toUpperCase()) : (String) maps.get(a[0].toLowerCase());
                    }
                    if (!StringUtils.checkNull(userName)) {
                        if (userName.contains("|")) {
                            String uNames[] = userName.split("\\|");
                            String userIds = uNames[0];
                            autoTypelist = usersService.getUserByuserId(userIds);
                        } else if (userName.contains("_")) {
                            String u1 = userName.substring(userName.indexOf("_") + 1, userName.length());
                            aUser = usersService.getUserByUserName(u1);
                            if (aUser != null) {
                                autoTypelist.add(aUser);
                            }
                        } else {
                            String usName[] = userName.split(",");
                            for (int i = 0; i < usName.length; i++) {
                                aUser = usersService.getUserByUserName(usName[i]);
                                if (aUser != null) {
                                    autoTypelist.add(aUser);
                                }
                            }
                        }
                    }
                }
                break;
            case 8://指定步骤主办人
                //获取指定步骤
                Integer step = flowProcess.getAutoBaseUser();
                String userId = wfeFlowRunPrcs.getUserIdByMaxFlowPrcs(step, Integer.parseInt(runId));
                if (!StringUtils.checkNull(userId)) {
                    Users users1 = usersService.findUsersByuserId(userId);
                    autoTypelist.add(users1);
                    return autoTypelist;
                }
                break;
            case 9://自动选择本部门助理
                //0代表当前步骤
                if (autoBaseUser == 0) {
                    department = departmentService.getDeptById(users.getDeptId());
                    if (!StringUtils.checkNull(department.getAssistantId()) && department.getAssistantId().split(",").length > 0) {
                        autoTypelist = usersService.getUserByuserId(department.getAssistantId().split(",")[0]);
                    }
                } else {
                    for (FlowRunPrcs flowRunPrcs : allfrp) {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users u1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getDeptById(u1.getDeptId());
                            if (!StringUtils.checkNull(department.getAssistantId())
                                    && department.getAssistantId().split(",").length > 0) {
                                autoTypelist = usersService.getUserByuserId(department.getAssistantId().split(",")[0]);
                            }
                            break;
                        }
                    }
                }
                break;
            case 10://自动选择本部门内符合条件所有人
                //0代表当前步骤
                if (autoBaseUser == 0) {
                    department = departmentService.getDeptById(users.getDeptId());
                    list = usersService.getUsersByDeptId(department.getDeptId());
                    for (Users users1 : list) {
                        if (flowProcess.getPrcsUser() != null && flowProcess.getPrcsUser().contains(users1.getUserId()) ||
                                flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptId().toString()) ||
                                flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPriv().toString()) ||
                                flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptIdOther()) ||
                                flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPrivOther())) {
                            autoTypelist.add(users1);
                        }
                    }
                } else {
                    for (FlowRunPrcs flowRunPrcs : allfrp) {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users u1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getDeptById(u1.getDeptId());
                            list = usersService.getUsersByDeptId(department.getDeptId());
                            for (Users users1 : list) {
                                if (flowProcess.getPrcsUser() != null && flowProcess.getPrcsUser().contains(users1.getUserId()) ||
                                        flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptId().toString()) ||
                                        flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPriv().toString()) ||
                                        flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptIdOther()) ||
                                        flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPrivOther())) {
                                    autoTypelist.add(users1);
                                }
                            }
                            break;
                        }
                    }
                }
                break;
            case 11://自动选择本一级部门内符合条件所有人员
                //0代表当前步骤
                if (autoBaseUser == 0) {
                    department = departmentService.getFatherDept(users.getDeptId());
                    list = usersService.getUsersByDeptId(department.getDeptId());
                } else {
                    for (FlowRunPrcs flowRunPrcs : allfrp) {
                        if (flowRunPrcs.getFlowPrcs().equals(autoBaseUser)) {
                            Users u1 = usersService.findUsersByuserId(flowRunPrcs.getUserId());
                            department = departmentService.getFatherDept(u1.getDeptId());
                            list = usersService.getUsersByDeptId(department.getDeptId());
                        }
                    }
                }
                for (Users users1 : list) {
                    if (flowProcess.getPrcsUser() != null && flowProcess.getPrcsUser().contains(users1.getUserId()) ||
                            flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptId().toString()) ||
                            flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPriv().toString()) ||
                            flowProcess.getPrcsDept() != null && flowProcess.getPrcsDept().contains(users1.getDeptIdOther()) ||
                            flowProcess.getPrcsPriv() != null && flowProcess.getPrcsPriv().contains(users1.getUserPrivOther())) {

                        autoTypelist.add(users1);
                    }
                }
                break;
            case 12://自动选择指定部门主管
                if (!StringUtils.checkNull(flowProcess.getAutoDept())) {
                    department = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                    if (!StringUtils.checkNull(department.getManager())) {
                        autoTypelist = usersService.getUserByuserId(department.getManager());
                    }
                }

                break;
            case 13://自动选择指定部门助理
                if (!StringUtils.checkNull(flowProcess.getAutoDept())) {
                    department = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                    if (!StringUtils.checkNull(department.getAssistantId())) {
                        autoTypelist = usersService.getUserByuserId(department.getAssistantId());
                    }
                }

                break;
            case 14://自动选择指定部门上级主管领导
                if (!StringUtils.checkNull(flowProcess.getAutoDept())) {
                    department = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                    //dparent = departmentService.getDeptById(department.getDeptParent());
                    if (!StringUtils.checkNull(department.getLeader1())) {
                        autoTypelist = usersService.getUserByuserId(department.getLeader1());
                    }
                }

                break;
            case 15://自动选择指定部门上级分管领导
                if (!StringUtils.checkNull(flowProcess.getAutoDept())) {
                    department = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                    // dparent = departmentService.getDeptById(department.getDeptParent());
                    if (!StringUtils.checkNull(department.getLeader2())) {
                        autoTypelist = usersService.getUserByuserId(department.getLeader2());
                    }
                }
                break;
            default:
                return autoTypelist;
        }
        if (autoTypelist != null && autoTypelist.size() > 0) {
            if (autoType != 3) {
                autoTypelist.get(0).setOpFlag("1");
            }
        }
        return autoTypelist;
    }


    public AjaxJson getHistoryFlowRunDatas(Integer flowId, Integer runId, String itemId, String searchValue) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            if (runId == null) {
                if (null == flowId || flowId == 0 || StringUtils.checkNull(itemId) || !itemId.startsWith("DATA_") || !checkNum(itemId)) {
                    ajaxJson.setMsg("传参异常");
                    ajaxJson.setFlag(false);
                } else {
                    String tableName = "flow_data_" + flowId;
                    List<Map<String, String>> mapList = workMapper.getHistoryFlowRunDatas(tableName, itemId, searchValue);
                    ajaxJson.setObj(mapList);
                    ajaxJson.setFlag(true);
                    ajaxJson.setMsg("OK");
                }
            } else {
                if (null == flowId || flowId == 0) {
                    ajaxJson.setMsg("传参异常");
                    ajaxJson.setFlag(false);
                } else {
                    Map<String, Object> maps = new HashMap<String, Object>();
                    maps.put("tableName", "flow_data_" + flowId);
                    maps.put("runId", runId);
                    maps = workMapper.select(maps);
                    ajaxJson.setObj(maps);
                    ajaxJson.setFlag(true);
                    ajaxJson.setMsg("OK");
                }
            }

        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
        }
        return ajaxJson;
    }

    public static boolean checkNum(String itemId) {
        if (!itemId.contains("DATA_")){
            return false;
        }
        String number = itemId.split("DATA_")[1];
        if (number != null && !"".equals(number.trim())) {
            return number.matches("^[0-9]*$");
        } else {
            return false;
        }

    }


    public AjaxJson getBranch(Integer flowId, Integer currentFlowPrcs, Integer runId, Users users) {
        AjaxJson ajaxJson = new AjaxJson();
        //定义流程下一步骤获取的所有对象
        Map<Integer, Map<String, Object>> reMap = new HashMap<Integer, Map<String, Object>>();
        //定义获取步骤对应流程信息
        Map<String, Object> temp = null;
        //用来传参取数据
        Map<String, Object> maprunId = new HashMap<String, Object>();
        try {
            maprunId.put("runId", runId);
            //根据流水号获取流程信息
            List<FlowRunPrcs> allFrp = wfeFlowRunPrcs.findByRunId(maprunId);
            Department dep = departmentService.getDeptById(users.getDeptId());
            //获取所有流程步骤
            Map<String, FlowProcess> map = this.allflowProcessBymap(flowId);
            //获取当前流程
            FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, currentFlowPrcs);
            FlowProcess nextFp = null;
            String prcsTo = flowProcess.getPrcsTo();
            if (StringUtils.checkNull(prcsTo)) {
                nextFp = map.get(flowProcess.getPrcsId() + 1 + "");
                temp = reTemp(nextFp, dep, users, runId, allFrp);
                reMap.put(nextFp == null ? 0 : nextFp.getPrcsId(), temp);
            } else {
                String[] prcsToArray = prcsTo.split(",");
                for (int i = 0, length = prcsToArray.length; i < length; i++) {
                    if (!"0".equals(prcsToArray[i])) {
                        nextFp = map.get(prcsToArray[i]);
                        temp = reTemp(nextFp, dep, users, runId, allFrp);
                        reMap.put(nextFp == null ? 0 : nextFp.getPrcsId(), temp);
                    }
                }
            }
            ajaxJson.setObj(reMap);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(true);
        }
        return ajaxJson;
    }

    /**
     * 转交下一步流程参数
     *
     * @param nextFp 流程设置步骤
     * @param dep    部门
     * @param users  用户
     * @param runId  流水号
     * @param allFrp
     * @return
     */
    public Map<String, Object> reTemp(FlowProcess nextFp, Department dep, Users users, Integer runId, List<FlowRunPrcs> allFrp) {
        Map<String, Object> temp = new HashMap<String, Object>();
        List<Users> autoTypelist = new ArrayList<Users>();
        if (null == nextFp) {
            temp.put("prcsName", "结束流程");
        } else {
            temp.put("prcsName", nextFp.getPrcsName());
            temp.put("prcsIn", nextFp.getPrcsIn());
            temp.put("prcsInSet", nextFp.getPrcsInSet());
            temp.put("conditionDesc", nextFp.getConditionDesc());
            temp.put("userLock", nextFp.getUserLock());
            temp.put("topDefault", nextFp.getTopDefault());
            temp.put("gatherNode", nextFp.getGatherNode());
            temp.put("flowPrcs", nextFp.getPrcsId());
            temp.put("syncDeal", nextFp.getSyncDeal());

            FlowRun flowRun = wfeFlowRun.find(runId);
            String preSetUser = flowRun.getPresetUser();
            if (StringUtils.checkNull(preSetUser)){
                if (!StringUtils.checkNull(nextFp.getAutoType())) {
                    autoTypelist = this.getAutoTypelist(dep, users, runId.toString(), nextFp, allFrp);
                }
            }else{
                preSetUser = this.getPrseSetUser(preSetUser,nextFp.getPrcsId().toString());
                autoTypelist = usersService.getUserByuserId(preSetUser);
            }

            if (autoTypelist == null || autoTypelist.size() == 0) {
                List<Integer> allUid = this.getWorkFlowUid(nextFp.getFlowId(), nextFp.getPrcsId(), users, null);
                if (allUid != null && allUid.size() == 1) {
                    Users autoUser = usersMapper.getByUid(allUid.get(0));
                    autoTypelist.add(autoUser);
                }
            }
            //是否设置了经办权限，如未设置，智能选人范围为全体人员，若有经办权限，智能选人范围在经办权限内
            if (StringUtils.checkNull(nextFp.getPrcsUser()) && StringUtils.checkNull(nextFp.getPrcsDept()) && StringUtils.checkNull(nextFp.getPrcsPriv())) {
                temp.put("autoTypelist", autoTypelist);
            } else {
                //获取deptNo
                List<Department> departmentByClassifyOrg = departmentService.getDepartmentByClassifyOrg(users, false, true);
                StringBuffer str = new StringBuffer();
                for (Department deps : departmentByClassifyOrg
                ) {
                    str.append(deps.getDeptNo() + ",");
                }
                PageParams page = new PageParams();
                page.setUseFlag(false);
                //获取下步流程所有经办人
                AjaxJson workFlowUser = this.getWorkFlowUser(nextFp.getFlowId(), nextFp.getPrcsId(), users, null, null, str.toString(), null, page);
                Map<Integer, Users> m = new LinkedHashMap<Integer, Users>();
                List<Users> usersList = null;
                if (workFlowUser.isFlag()) {//返回数据正确
                    usersList = (List<Users>) workFlowUser.getObj();
                    for (Users users1 : usersList) {
                        m.put(users1.getUid(), users1);
                    }
                    List<Users> resultList = new ArrayList();
                    if (autoTypelist != null && autoTypelist.size() > 0) {
                        for (Users users1 : autoTypelist) {
                            if (m.containsKey(users1.getUid())) {
                                resultList.add(users1);
                            }
                        }
                    }
                    temp.put("autoTypelist", resultList);
                } else {
                    temp.put("autoTypelist", autoTypelist);
                }

            }
        }
        return temp;
    }

    /**
     * @param flowId
     * @param flowPrcs
     * @param type
     * @param target
     * @param user
     * @return
     */
    public AjaxJson getWorkFlowUser(Integer flowId, Integer flowPrcs, Integer type, Integer target, Users user) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Users> temp = new ArrayList<Users>();
        try {
          /*  List<Integer> allUid = this.getWorkFlowUid(flowId, flowPrcs, user);
            if (allUid != null || allUid.size() > 0) {
                map.put("allUid", allUid);
                if (1 == type){
                    map.put("deptId", target);
                }else if(2 == type){
                    map.put("userPriv", target);
                }
                temp = usersService.getWorkFlowUser(map);
            }
            ajaxJson.setObj(temp);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");*/
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
        }
        return ajaxJson;
    }

    /**
     * 工作流转交选人获取可选人员uid串
     *
     * @param flowId   流程编号
     * @param flowPrcs 流程设计步骤
     * @param user     用户
     * @return uid的list集合
     */
    public List<Integer> getWorkFlowUid(Integer flowId, Integer flowPrcs, Users user, String deptNo) {
        //获取当前步骤对应流程设计步骤
        FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, flowPrcs);
        //获取所有经办人
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("flowId", flowProcess.getFlowId());
        map.put("prcsId", flowProcess.getPrcsId());
        map.put("prcsPriv", flowProcess.getPrcsPriv() == "" ? null : flowProcess.getPrcsPriv().split(","));
        map.put("prcsDept", flowProcess.getPrcsDept() == "" ? null : flowProcess.getPrcsDept().split(","));

        if ("" != flowProcess.getUserFilter().trim() && !"0".equals(flowProcess.getUserFilter().trim())) {
            Integer userFilter = Integer.parseInt(flowProcess.getUserFilter());
            //允许选择的经办人
            List<Integer> userFilterlist = getFilterlist(userFilter, user, flowProcess);
            if (userFilterlist == null || userFilterlist.size() == 0) {
                return userFilterlist;
            }
            map.put("userFilter", userFilterlist);
        }
        if (!StringUtils.checkNull(deptNo)) {
            //如果范围是分级机构
            String[] deptNoStr = deptNo.split(",");
            map.put("deptNo", deptNoStr);
            //获取分支部门的id号
            List<Integer> deptIdByNo = departmentService.getDeptByDeptNoStr(deptNoStr);
            map.put("deptIdByNo", deptIdByNo);
        }

        //获取符合条件用户的uid
        List<Integer> allUid = usersService.getWorkFlowUid(map);
        return allUid;
    }


    public AjaxJson signControl(Integer runId, Integer flowId, String signdata) {

        AjaxJson ajaxJson = new AjaxJson();

        String tableName = "flow_data_" + flowId;
        //用来存储sql传入参数
        Map<String, Object> param = new HashMap();
        List<String> key = new ArrayList<String>();
        try {
            //表单上所有的数据
            List<Map<String, Object>> dataList = JSONArray.parseObject(signdata, List.class);
            Map<String, Object> countersignDataMap = null;
            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse");
            List<String> data = new ArrayList<String>();
            Map<String, Object> maps = new HashMap<String, Object>();
            maps.put("tableName", tableName);
            maps.put("tableSchema", sqlType);
            List<String> columns = workMapper.showColumns(maps);//所有列
            for (Map<String, Object> map : dataList) {
                String key1 = map.get("key").toString();
                String value1 = map.get("value").toString();
                if (!columns.contains(key1)) {//没有对应的列，则新建列
                    Map<String, Object> map2 = new HashMap<>();
                    List<String> str = new ArrayList<>();
                    str.add(key1);
                    map2.put("tableName", tableName);
                    map2.put("keys", str);
                    workMapper.addcolumn(map2);
                }
                data.add(key1);
                countersignDataMap = workMapper.getDataValue(data, runId, tableName);

                //判断审批意见控件是否有值
                if(null!=value1&&!value1.equals("")){

                    Document documentShuJuKu=Jsoup.parse(countersignDataMap.get(key1).toString());
                    Elements eiderareaShuJuKu = documentShuJuKu.getElementsByClass("eiderarea");

                    //表单填写传来的的审批意见
                    Document documentFrom=Jsoup.parse(value1);
                    String user_idFrom = documentFrom.getElementsByClass("eiderarea").last().attr("user_id");
                    String prcs_idFrom = documentFrom.getElementsByClass("eiderarea").last().attr("prcs_id");
                    if(!value1.equals("")&&!user_idFrom.equals("")&&!prcs_idFrom.equals("")){
                        //遍历添加意见
                        LinkedList<String> linkedList=new LinkedList<>();
                        for(Element element: eiderareaShuJuKu){
                            linkedList.addLast(element.toString());
                        }

                        //替换意见
                        //数据库最后一个人的审批意见
                        Document documentShuJuKu2=Jsoup.parse(linkedList.getLast());
                        String user_idFrom2 = documentShuJuKu2.getElementsByClass("eiderarea").eq(0).attr("user_id");
                        String prcs_idFrom2 = documentShuJuKu2.getElementsByClass("eiderarea").eq(0).attr("prcs_id");
                        if(user_idFrom2.equals(user_idFrom)&&prcs_idFrom.equals(prcs_idFrom2)){
                            linkedList.removeLast();
                            linkedList.addLast(value1);
                        }else {
                            linkedList.addLast(value1);
                        }


                        //拼接

                        StringBuilder stringBuilder=new StringBuilder();
                        for (int i=0;i<linkedList.size();i++){

                            stringBuilder.append(linkedList.get(i));
                        }
                        key.add(key1 + "=" + "'" + stringBuilder.toString() + "'");
                    }

                }else{
                    key.add(key1 + "=" + "'" + countersignDataMap.get(key1) + "'");
                }


            }
            param.put("tableName", tableName);
            param.put("keys", key);
            param.put("runId", String.valueOf(runId));
            workMapper.update(param);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.setFlag(false);
            ajaxJson.setMsg("false");
        }
        return ajaxJson;

    }


    /**
     * @创建作者:李然 Lr
     * @方法描述：结束子流程返回父流程情况
     * @创建时间：10:42 2019/6/25
     **/
    public ToJson finishSonReturnParent(HttpServletRequest request) {
        ToJson toJson = new ToJson(1, "err");
        String sonRunId = request.getParameter("runId");//子流程runId
        String parentFlowPrcs = request.getParameter("parentFlowPrcs");//返回父流程的步骤
        String beginUser = request.getParameter("beginUser");
        String jingbanUser = request.getParameter("jingbanUser");
        String topFlag = request.getParameter("topDefault");
        if (topFlag != null) {
            topFlag = topFlag.split(",")[0];
        }
        //此时有两种情况
        //一、 返回步骤不为强制合并，此时直接创建父流程步骤即可
        Map<String, Object> parentMap = new HashMap<>();
        parentMap.put("childRun", sonRunId);
        //查找父流程实例
        FlowRunPrcs flowRunPrcs = flowRunPrcsMapper.selectParentFlowRunPrcs(parentMap);
        if (flowRunPrcs != null) {
            if (beginUser != null) {
                String[] beginUserArray = beginUser.split(",");//也许将来会有多个主办人
                for (String begin : beginUserArray) {
                    if (begin != null && !begin.trim().equals("")) {
                        //获取prcsId最大的
                        List<FlowRunPrcs> flowRunPrcsList = flowRunPrcsMapper.findMaxFrp(flowRunPrcs.getRunId());
                        Users users = usersMapper.getUsersByuserId(begin);
                        FlowRunPrcs flowRunPrcsOpFalg = new FlowRunPrcs(flowRunPrcs.getRunId(), flowRunPrcsList.get(0).getPrcsId() + 1, begin, null, "0000-00-00 00:00:00",
                                "1", Integer.valueOf(parentFlowPrcs), "1", topFlag, DateFormat.getStrDate(new Date()), "0000-00-00 00:00:00", users.getDeptId(), flowRunPrcs.getFlowPrcs() + "");
                        wfeFlowRunPrcs.save(flowRunPrcsOpFalg);
                    }
                }
            }

            if (jingbanUser != null) {
                String[] jingbanArray = jingbanUser.split(",");
                for (String jingban : jingbanArray) {
                    if (!jingban.equals(String.valueOf(beginUser)) && !String.valueOf(beginUser).contains(jingban + ",")) {
                        //获取prcsId最大的
                        List<FlowRunPrcs> flowRunPrcsList = flowRunPrcsMapper.findMaxFrp(flowRunPrcs.getRunId());
                        Users users = usersMapper.getUsersByuserId(jingban);
                        FlowRunPrcs flowRunPrcsFalg = new FlowRunPrcs(flowRunPrcs.getRunId(), flowRunPrcsList.get(0).getPrcsId(), jingban, null, "0000-00-00 00:00:00",
                                "1", Integer.valueOf(parentFlowPrcs), "0", topFlag, DateFormat.getStrDate(new Date()), "0000-00-00 00:00:00", users.getDeptId(), flowRunPrcs.getFlowPrcs() + "");
                        wfeFlowRunPrcs.save(flowRunPrcsFalg);
                    }
                }

            }

            toJson.setFlag(0);
            toJson.setMsg("ok");

            //先父流程判断是否转交公文正文
            List<FlowProcess> flowProcesses = flowProcessMapper.selectRelationIn(String.valueOf(flowRunPrcs.getRunId()));//判断父流程是否转交公文正文
            String sqlType = "xoa" + (String) request.getSession().getAttribute(

                    "loginDateSouse");
            if (StringUtils.checkNull((String) request.getSession().getAttribute(
                    "loginDateSouse"))) {
                sqlType = "xoa1001";
            }
            String str4 = "";
            String str5 = "";
            String str6 = "";
            for (FlowProcess flow1 : flowProcesses) {
                int result4 = flow1.getRelationOut().indexOf("公文正文=>公文正文");
                int result5 = flow1.getRelationOut().indexOf("流程附件=>公文正文");
                int result6 = flow1.getRelationOut().indexOf("流程附件=>流程附件");

                if (-1 != result4) {
                    str4 = "子父公文正文";
                }
                if (-1 != result5) {
                    str5 = "子流程公文正文到父流程附件";
                }
                if (-1 != result6) {
                    str6 = "子父附件到附件";
                }

            }
            FlowRun son = wfeFlowRun.find(Integer.parseInt(sonRunId));
            FlowRun parent = wfeFlowRun.find(flowRunPrcs.getRunId());
            FlowRun sonFlowRun = wfeFlowRun.find(Integer.parseInt(sonRunId));
            FileUploadUtil fileUploadUtil = new FileUploadUtil();
            List<Attachment> fathAttach = new ArrayList<Attachment>();//先设置空的正文
            if (!"子父公文正文".equals(str4)) {
                DocumentMapper.updateDocumentAttach(parent.getRunId());//把父公文正文设置为空
            }

            if ("子流程公文正文到父流程附件".equals(str5)) {
                //获取子公文实体类
                DocumentModel fathDocument = documentSerivce.checkRunId(sonFlowRun.getRunId());
                //获取子公文的正文
                if (StringUtils.checkNull(fathDocument.getMainAipFile())) {//判断api为空
                    fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainFileName(), fathDocument.getMainFile(), sqlType, "document");
                } else {
                    fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainAipFileName(), fathDocument.getMainAipFile(), sqlType, "document");
                }
                //复制文件
                List<Attachment> sonAttach = fileUploadUtil.cppyFiles(fathAttach, sqlType, "document");
                for (Attachment attachment : sonAttach) {
                    enclosureService.saveAttachment(attachment);
                }
                Object[] o = FileUploadUtil.reAttachment(sonAttach);//返回子流程附件信息

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("runId", flowRunPrcs.getRunId());//获取父流程id


                if (StringUtils.checkNull(parent.getAttachmentId())) {//父流程附件为空，进行子流程附件复制
                    if (!StringUtils.checkNull(son.getAttachmentId())) {
                        if (!",".equals(son.getAttachmentId().substring(son.getAttachmentId().length() - 1, son.getAttachmentId().length()))) {
                            son.setAttachmentId(son.getAttachmentId() + ",");
                        }
                    }
                    if ("".equals(str6)) {//不传子流程附件
                        son.setAttachmentId("");
                    }
                    parent.setAttachmentId(son.getAttachmentId() + parent.getAttachmentId());
                } else {//父流程不为空  进行子流程附件复制
                    if (!StringUtils.checkNull(son.getAttachmentId())) {
                        if (!",".equals(son.getAttachmentId().substring(son.getAttachmentId().length() - 1, son.getAttachmentId().length()))) {
                            son.setAttachmentId(son.getAttachmentId() + ",");
                        }
                    }
                    if ("".equals(str6)) {//不传子流程附件
                        son.setAttachmentId("");
                    }
                    parent.setAttachmentId(son.getAttachmentId() + parent.getAttachmentId());
                }

                if (StringUtils.checkNull(parent.getAttachmentName())) {//fu流程为空  进行zi流程附件name复制
                    if (!StringUtils.checkNull(son.getAttachmentName())) {
                        if (!"*".equals(son.getAttachmentName().substring(son.getAttachmentName().length() - 1, son.getAttachmentName().length()))) {
                            son.setAttachmentName(son.getAttachmentName() + "*");
                        }
                    }
                    if ("".equals(str6)) {//不传子流程附件
                        son.setAttachmentName("");
                    }
                    parent.setAttachmentName(son.getAttachmentName() + parent.getAttachmentName());
                } else {//fu流程不为空  进行zi流程附件name复制
                    if (!StringUtils.checkNull(son.getAttachmentId())) {
                        if (!",".equals(son.getAttachmentId().substring(son.getAttachmentId().length() - 1, son.getAttachmentId().length()))) {
                            son.setAttachmentId(son.getAttachmentId() + ",");
                        }
                    }
                    if ("".equals(str6)) {
                        son.setAttachmentName("");
                    }
                    parent.setAttachmentName(son.getAttachmentName() + parent.getAttachmentName());
                }

                map.put("attachmentId", parent.getAttachmentId() + o[0].toString());
                map.put("attachmentName", parent.getAttachmentName() + o[1].toString());
                wfeFlowRun.updateAttachment(map);
            }
            if ("子父附件到附件".equals(str6) && "".equals(str5)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("runId", flowRunPrcs.getRunId());
                if (StringUtils.checkNull(parent.getAttachmentId())) {//父流程附件为空，进行子流程附件复制
                    if (!StringUtils.checkNull(son.getAttachmentId())) {
                        if (!",".equals(son.getAttachmentId().substring(son.getAttachmentId().length() - 1, son.getAttachmentId().length()))) {
                            son.setAttachmentId(son.getAttachmentId() + ",");
                        }
                    }
                    if ("".equals(str6)) {//不传子流程附件
                        son.setAttachmentId("");
                    }
                    parent.setAttachmentId(son.getAttachmentId() + parent.getAttachmentId());
                } else {//父流程不为空  进行子流程附件复制
                    if (!StringUtils.checkNull(son.getAttachmentId())) {
                        if (!",".equals(son.getAttachmentId().substring(son.getAttachmentId().length() - 1, son.getAttachmentId().length()))) {
                            son.setAttachmentId(son.getAttachmentId() + ",");
                        }
                    }
                    if ("".equals(str6)) {//不传子流程附件
                        son.setAttachmentId("");
                    }
                    parent.setAttachmentId(son.getAttachmentId() + parent.getAttachmentId());
                }

                if (StringUtils.checkNull(parent.getAttachmentName())) {//fu流程为空  进行zi流程附件name复制
                    if (!StringUtils.checkNull(son.getAttachmentName())) {
                        if (!"*".equals(son.getAttachmentName().substring(son.getAttachmentName().length() - 1, son.getAttachmentName().length()))) {
                            son.setAttachmentName(son.getAttachmentName() + "*");
                        }
                    }
                    if ("".equals(str6)) {//不传子流程附件
                        son.setAttachmentName("");
                    }
                    parent.setAttachmentName(son.getAttachmentName() + parent.getAttachmentName());
                } else {//fu流程不为空  进行zi流程附件name复制
                    if (!StringUtils.checkNull(son.getAttachmentId())) {
                        if (!",".equals(son.getAttachmentId().substring(son.getAttachmentId().length() - 1, son.getAttachmentId().length()))) {
                            son.setAttachmentId(son.getAttachmentId() + ",");
                        }
                    }
                    if ("".equals(str6)) {
                        son.setAttachmentName("");
                    }
                    parent.setAttachmentName(son.getAttachmentName() + parent.getAttachmentName());
                }

                map.put("attachmentId", parent.getAttachmentId());
                map.put("attachmentName", parent.getAttachmentName());
                wfeFlowRun.updateAttachment(map);
            }
            try {
                //进行子到父映射
                FlowRun sonFlowRuns = flowRunMapper.find(Integer.parseInt(sonRunId));
                FlowRun parentFlowRun = flowRunMapper.find(flowRunPrcs.getRunId());
                FlowProcess flowProcess = wfeFlowProcessMapper.findProcess(parentFlowRun.getFlowId(), flowRunPrcs.getFlowPrcs());
                mapping(parentFlowRun, sonFlowRuns, 1, flowProcess);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        } else {
            //父流程实例以不存在
        }
        return toJson;
    }

    //公共映射方法。type 0  为父到子，1为子到父
    public void mapping(FlowRun parentFlowRun, FlowRun sonFlowRun, Integer type, FlowProcess flowProcess) {
        if (parentFlowRun != null && sonFlowRun != null) {
            //头表单
            Document headDoc = null;
            //尾表单
            Document endDoc = null;
            String relation = null;
            Map<String, Document> documentMap = null;
            FlowRun headFlowRun = null;//头实例
            FlowRun endFlowRun = null;//尾实例
            //查看type类型   如果为1则为子到父映射。否责为父到子映射
            if (type == 1) {
                relation = flowProcess.getRelationOut();
                //得到头尾表单  子到父  子为head
                documentMap = flowMapping(sonFlowRun, parentFlowRun);
                headFlowRun = sonFlowRun;
                endFlowRun = parentFlowRun;
            } else {
                relation = flowProcess.getRelationIn();
                //得到头尾表单  父到子  父为head
                documentMap = flowMapping(parentFlowRun, sonFlowRun);
                headFlowRun = parentFlowRun;
                endFlowRun = sonFlowRun;
            }
            headDoc = documentMap.get("headDocument");
            endDoc = documentMap.get("endDocument");

            if (relation != null && !relation.equals("")) {
                //根据，隔开得到多个映射关系
                String[] mappingArray = relation.split(",");

                List<String> key = new ArrayList<>();
                List<String> value = new ArrayList<>();
                for (String mapping : mappingArray) {
                    String[] mappingHeadAndEnd = mapping.split("=>");
                    if (mappingHeadAndEnd.length > 1) {
                        String mappingHead = mappingHeadAndEnd[0];//映射头
                        String mappingEnd = mappingHeadAndEnd[1];//映射尾
                        String headData = HtmlUtil.getDocumentName(headDoc, mappingHead);
                        String endData = HtmlUtil.getDocumentName(endDoc, mappingEnd);
                        if (headData != null && !headData.trim().equals("")) {
                            if (endData != null && !endData.trim().equals("")) {
                                key.add(headData);
                                value.add(endData);
                            }
                        }

                    }

                }
                List<String> values = new ArrayList<>();
                if (key.size() > 0) {
                    Map<String, Object> valueMap = workMapper.getDataValue(key, headFlowRun.getRunId(), "flow_data_" + headFlowRun.getFlowId());
                    if (valueMap != null) {
                        for (String k : key) {
                            Object v = valueMap.get(k);
                            if (v != null) {
                                values.add(String.valueOf(v));
                            } else {
                                values.add("");
                            }
                        }
                    }
                }
                if (value.size() > 0 && values.size() > 0) {
                    String setSql = null;
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < value.size(); i++) {
                        sb.append(value.get(i) + "=" + "'" + values.get(i) + "'" + ",");
                    }
                    if (sb.charAt(sb.length() - 1) == ',') {
                        setSql = sb.substring(0, sb.length() - 1);
                    }
                    if (setSql != null) {
                        workMapper.updateDataValue(setSql, "flow_data_" + endFlowRun.getFlowId(), endFlowRun.getRunId());
                    }
                }
            }
        }
    }

    public Map<String, Document> flowMapping(FlowRun headFlowRun, FlowRun endFlowRun) {
        //查询头数据表单
        Integer headFlowId = headFlowRun.getFlowId();
        FlowTypeModel headFlowType = flowTypeModelMapper.queryOneObject(headFlowId);
        FlowFormType headFlowForm = flowFormTypeMapper.qureyItemMax(headFlowType.getFormId());
        //获得具体的表单数据  头表单
        String headPrintModel = headFlowForm.getPrintModel();
        //解析表单 头表单
        Document headDocument = getField(headPrintModel);

        //查询尾表表单
        Integer endFlow = endFlowRun.getFlowId();
        FlowTypeModel endFlowType = flowTypeModelMapper.queryOneObject(endFlow);
        FlowFormType endFlowForm = flowFormTypeMapper.qureyItemMax(endFlowType.getFormId());
        //获得具体的表单数据 尾表单
        String endPrintModel = endFlowForm.getPrintModel();
        //解析表单
        // 尾表单
        Document endDocument = getField(endPrintModel);
        Map<String, Document> documentMap = new HashMap<>();
        documentMap.put("headDocument", headDocument);
        documentMap.put("endDocument", endDocument);

        return documentMap;
    }


    public ToJson<FlowRunPrcs> savework(Integer runId, String runName, Integer prcsId,
                                        String flowPrcs, String beginTime, String beginUser, String jingbanUser, String viewUser, Users users,
                                        Integer currentPrcsId, String topDefault, String tabId, String tableName,
                                        String smsContent, String smsType, String orgadd) {
        ToJson<FlowRunPrcs> toJson = new ToJson<FlowRunPrcs>();
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            FlowRun flowRun = wfeFlowRun.find(runId);
            Integer flowId = flowRun.getFlowId();
            //当前步骤对应流程和实例基本信息
            FlowProcess currentFp = wfeFlowProcess.findbyprcsId(flowId, currentPrcsId);

            //当前步骤状态，强制转交、传阅，触发器业务逻辑方法

            TriggerPlugIn triggerPlugIn = this.updateFlowRunPrcs(runId, prcsId, flowPrcs, currentPrcsId, users.getUserId(), currentFp.getTopDefault(), flowRun,
                    viewUser, tabId, beginUser, beginTime, runName);
            toJson.setObj1(triggerPlugIn.getNotifyId());
            FlowRunPrcs fl = new FlowRunPrcs();

            //流程结束
            if (("0").equals(flowPrcs)) {
                //判断是否有父流程
                Map<String, Object> parentMap = new HashMap<>();
                parentMap.put("childRun", runId);
                FlowRunPrcs parentFlowRunPrcs = flowRunPrcsMapper.selectParentFlowRunPrcs(parentMap);
                if (parentFlowRunPrcs != null) {//如果有父流程
                    FlowRun flowRun1 = wfeFlowRun.find(parentFlowRunPrcs.getRunId());
                    FlowProcess process = wfeFlowProcessMapper.findProcess(flowRun1.getFlowId(), parentFlowRunPrcs.getFlowPrcs());
                    FlowSort flowSort = flowSortMapper.getFlowSortByFlowId(flowRun1.getFlowId());
                    SmsBody smsBody = new SmsBody();
                    String title = "";
                    String context = "";
                    String remindUrl = "";
                    boolean bol = false;
                    SysPara myproject = sysParaMapper.querySysPara("MYPROJECT");
                    if (myproject != null && !StringUtils.checkNull(myproject.getParaValue())
                            && "dazu".equals(myproject.getParaValue())) {
                        bol = true;
                    }
                    if (!StringUtils.checkNull(beginUser)) {
                        if ("DOCUMENTTYPE".equals(flowSort.getSortMainType())) {
                            remindUrl = "/workflow/work/workform?opflag=1&flowId=" + flowRun1.getFlowId() + "&flowStep=" + (parentFlowRunPrcs.getPrcsId() + 1) + "&tableName=document&tabId=" + documentSerivce.checkRunId(flowRun1.getRunId()).getId() + "&runId=" + parentFlowRunPrcs.getRunId() + "&prcsId=" + Integer.parseInt(process.getPrcsTo()) + "&isNomalType=false";
                            System.out.print(remindUrl);
                            title = bol ? flowRun1.getRunName() : "您有新的公文需要签阅";
                            context = "流水号：" + runId + "，公文文号：" + flowRun1.getRunName();
                            smsBody = new SmsBody(users.getUserId(), "70", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
                        } else {
                            title = bol ? flowRun1.getRunName() : "您有新的工作需要办理";
                            context = "流水号：" + runId + "，工作名称/文号：" + flowRun1.getRunName();
                            remindUrl = "/workflow/work/workform?opflag=1&flowId=" + flowRun1.getFlowId() + "&flowStep=" + (parentFlowRunPrcs.getPrcsId() + 1) + "&runId=" + parentFlowRunPrcs.getRunId() + "&prcsId=" + Integer.parseInt(process.getPrcsTo());
                            smsBody = new SmsBody(users.getUserId(), "7", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
                        }
                        smsService.saveSms(smsBody, beginUser, "1", "1", title, context, "");
                    }
                    String[] jingbanUsers = jingbanUser.split(",");
                    for (String jingban : jingbanUsers) {
                        if ((!jingban.equals(String.valueOf(beginUser)))) {
                            if ("DOCUMENTTYPE".equals(flowSort.getSortMainType())) {
                                remindUrl = "/workflow/work/workform?opflag=0&flowId=" + flowRun1.getFlowId() + "&flowStep=" + (parentFlowRunPrcs.getPrcsId() + 1) + "&tableName=document&tabId=" + documentSerivce.checkRunId(flowRun1.getRunId()).getId() + "&runId=" + parentFlowRunPrcs.getRunId() + "&prcsId=" + Integer.parseInt(process.getPrcsTo()) + "&isNomalType=false";
                                System.out.print(remindUrl);
                                title = bol ? flowRun1.getRunName() : "您有新的公文需要签阅";
                                context = "流水号：" + runId + "，公文文号：" + flowRun1.getRunName();
                                smsBody = new SmsBody(users.getUserId(), "70", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
                            } else {
                                title = bol ? flowRun1.getRunName() : "您有新的工作需要办理";
                                context = "流水号：" + runId + "，工作名称/文号：" + flowRun1.getRunName();
                                remindUrl = "/workflow/work/workform?opflag=0&flowId=" + flowRun1.getFlowId() + "&flowStep=" + (parentFlowRunPrcs.getPrcsId() + 1) + "&runId=" + parentFlowRunPrcs.getRunId() + "&prcsId=" + Integer.parseInt(process.getPrcsTo());
                                smsBody = new SmsBody(users.getUserId(), "7", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
                            }
                            smsService.saveSms(smsBody, jingban, "1", "1", title, context, "");
                        }

                    }
                } else {
                    workService.todoWorkSmsBoby(beginUser, flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefault, smsContent, request, smsType, users, orgadd, jingbanUser, viewUser);
                }
                //结束流程
                ToJson toJson1 = this.endFlowRunPrcs(runId, prcsId, users.getUserId(), currentPrcsId, currentFp);
                toJson1.setObj1(triggerPlugIn.getNotifyId());
                return toJson1;
            }
            SysPara sysPara = sysParaMapper.querySysPara("MYPROJECT");
            String paraName = null;
            if (null != sysPara) {
                paraName = sysPara.getParaValue();
            }

            if (!"dazu".equals(paraName)) {
                if (!StringUtils.checkNull(viewUser)) {
                    if (smsType.contains("8") && smsType.contains("9")) {
                        workService.todoWorkSmsBoby(beginUser, flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefault, smsContent, request, "8,9,", users, orgadd, jingbanUser, viewUser);
                    } else {
                        if (smsType.contains("8")) {
                            workService.todoWorkSmsBoby(beginUser, flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefault, smsContent, request, "8", users, orgadd, jingbanUser, viewUser);
                        }
                        if (smsType.contains("9")) {
                            workService.todoWorkSmsBoby(beginUser, flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefault, smsContent, request, "9", users, orgadd, jingbanUser, viewUser);
                        }
                    }
                }
            }

            //下一步经办步骤
            String[] fpArray = flowPrcs.split(",");
            //经办人数组
            String[] alljingbanArray = jingbanUser.split("\\|");
            //主办人数组
            String[] beginUserArray = beginUser.split(",");
            //主办人相关选项数组
            String[] topDefaultArray = topDefault.split(",");

            //获取当前步骤数据
            List<FlowRunPrcs> listFrp = wfeFlowRunPrcs.selectFind(prcsId, runId, currentPrcsId, users.getUserId(), null);
            FlowRunPrcs currentFrp = listFrp.get(0);
            String branchCount = null;
            //根据是否允许并发判断并发步骤的值
            if (!"0".equals(currentFp.getSyncDeal().trim())) {
                branchCount = currentFp.getPrcsId().toString();
            } else {
                branchCount = currentFrp.getBranchCount();
            }
            if ("0".equals(currentFp.getSyncDeal().trim()) && "1".equals(currentFp.getGatherNode())) {
                branchCount = "0";
            }
            int length = fpArray.length;
            for (int i = 0; i < length; i++) {
                //步骤对应流程信息
                FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));

                if ("1".equals(flowProcess.getGatherNode())) {
                    int temp = length - 1;
                    if (i < temp) {
                        String tempFp = fpArray[i];
                        String tempBeginUser = beginUserArray[i];
                        String tempJingbanUser = alljingbanArray[i];
                        String tempTopDefault = topDefaultArray[i];
                        int len = temp - i;
                        for (int j = 0; j < len; j++) {
                            fpArray[i + j] = fpArray[i + j + 1];
                            if (beginUserArray.length>(i+j+1)){
                                beginUserArray[i + j] = beginUserArray[i + j + 1];
                            }else{
                                beginUserArray[i + j]="";
                            }
                            alljingbanArray[i + j] = alljingbanArray[i + j + 1];
                            topDefaultArray[i + j] = topDefaultArray[i + j + 1];
                        }
                        fpArray[temp] = tempFp;
                        if (beginUserArray.length>temp){
                            beginUserArray[temp] = tempBeginUser;
                        }
                        alljingbanArray[temp] = tempJingbanUser;
                        topDefaultArray[temp] = tempTopDefault;
                        //因为做了个排序，流程数组需要重新获取
                        flowProcess = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));

                    }

                }

                String[] jingbanArray = null;
                //对应步骤经办数组
                jingbanArray = alljingbanArray[i].split(",");
                //判断该步骤是否是主办

                String beginByUser = null;
                if (!"2".equals(topDefaultArray[i])) {
                    if (beginUserArray.length == 1) {
                        if (!StringUtils.checkNull(beginUserArray[0])) {
                            beginByUser = beginUserArray[0];
                        }
                    } else if (beginUserArray.length == 0) {

                    } else {
                        beginByUser = beginUserArray[i];
                    }
                } else if ("2".equals(topDefaultArray[i])) {//无主办人办理
                    if (jingbanArray.length > 0) {
                        //可能是无主办人有一个或多个
                        for (int j = 0; j < jingbanArray.length; j++) {
                            if (!StringUtils.checkNull(beginByUser)) {
                                beginByUser += jingbanArray[j] + ",";
                            } else {
                                beginByUser = jingbanArray[j] + ",";
                            }

                        }
                        String str = beginByUser.substring(beginByUser.length() - 1, beginByUser.length());
                        if (",".equals(str)) {
                            beginByUser = beginByUser.substring(0, beginByUser.length() - 1);
                        }
                    }
                }
                for (int j = 0; j < jingbanArray.length; j++) {

                    Integer child_run = null;
                    fl = new FlowRunPrcs();
                    //添加先接收着者主办
                    if ("1".equals(topDefaultArray[i])) {
                        fl.setOpFlag("1");
                    } else if ("2".equals(topDefaultArray[i])) {  //无主办人会签
                        fl.setOpFlag("0");
                    } else {
                        if (StringUtils.checkNull(beginByUser)) {
                            fl.setOpFlag("1");
                        } else {
                            if (beginByUser.equals(jingbanArray[j])) {
                                fl.setOpFlag("1");
                                //添加子流程
                                try {
                                    FlowProcess flowProcesscurrent = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));
                                    child_run = newFlowRun(flowProcesscurrent, runId.toString(), jingbanArray[j]);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                fl.setOpFlag("0");
                            }
                        }
                    }
                    if (child_run != null) {
                        //当前流程添加此子流程
                        fl.setChildRun(child_run);
                    }
                    fl.setTopFlag(topDefaultArray[i]);
                    fl.setRunId(runId);
                    fl.setPrcsId(prcsId + 1);
                    fl.setPrcsFlag("1");
                    fl.setFlowPrcs(Integer.parseInt(fpArray[i]));
                    //查看是否有委托规则
                    try {
                        String userId = getUserId(runId.toString(), jingbanArray[j]);
                        if (userId != null && userId != "") {
                            jingbanArray[j] = userId;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    fl.setUserId(jingbanArray[j]);
                    fl.setCreateTime(DateFormat.getStrDate(new Date()));
                    fl.setPrcsTime("0000-00-00 00:00:00");
                    fl.setDeliverTime("0000-00-00 00:00:00");
                    fl.setActiveTime("0000-00-00 00:00:00");
                    fl.setParent(currentPrcsId.toString());
                    fl.setParentPrcsId(prcsId.toString());
                    fl.setBranchCount(branchCount);
                    //强制合并
                    if ("1".equals(flowProcess.getGatherNode())) {
                        //检查该强制步骤是否存在未办理的流程
                        Integer check = wfeFlowRunPrcs.checkBranch(runId, branchCount, flowProcess.getPrcsId());
                        //查询强制合并步骤是否存在流程
                        List<FlowRunPrcs> list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), null, branchCount);
                        //获得强制合并步骤对应步骤
                        FlowRunPrcs flowRunPrcs = list.size() == 0 ? null : list.get(0);
                        //此段代码用以处理多次回退造成强制合并步骤显示错误问题
                        if (flowRunPrcs!=null){
                            if ("3".equals(flowRunPrcs.getPrcsFlag())||"4".equals(flowRunPrcs.getPrcsFlag())){
                                flowRunPrcs=null;
                            }
                        }

                        if (list != null && list.size() > 0&&flowRunPrcs!=null) {

                            if (check == null) {
                                //升位操作
                                if (fl.getPrcsId() > flowRunPrcs.getPrcsId()) {
                                    wfeFlowRunPrcs.updatePrcsId(runId, fl.getPrcsId(), null, "1", flowProcess.getPrcsId(), branchCount);
                                } else {
                                    wfeFlowRunPrcs.updatePrcsId(runId, null, null, "1", flowProcess.getPrcsId(), branchCount);
                                    fl.setPrcsId(flowRunPrcs.getPrcsId());
                                }

                            } else {
                                //升位操作
                                if (flowRunPrcs != null) {
                                    if (fl.getPrcsId() > flowRunPrcs.getPrcsId()) {
                                        wfeFlowRunPrcs.updatePrcsId(runId, fl.getPrcsId(), null, null, flowProcess.getPrcsId(), branchCount);
                                    } else {
                                        fl.setPrcsId(flowRunPrcs.getPrcsId());
                                    }
                                }
                                fl.setPrcsFlag("6");
                            }
                            String parent = flowRunPrcs.getParent();
                            String parentPrcsId = flowRunPrcs.getParentPrcsId();
                            //查询当前转交用户是否存在对应流程
                            list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), fl.getUserId(), branchCount);
                            //判断是否是先接收者主办情况
                            if (list == null || list.size() == 0) {
                                //判断是否是先接收者主办情况
                                if (!"1".equals(flowProcess.getTopDefault())) {
                                    fl.setOpFlag("0");
                                }
                                if (0 == j) {
                                    fl.setParent(parent + "," + fl.getParent());
                                    fl.setParentPrcsId(parentPrcsId + "," + fl.getParentPrcsId());
                                } else {
                                    fl.setParent(parent);
                                    fl.setParentPrcsId(parentPrcsId);
                                }
                                wfeFlowRunPrcs.save(fl);
                                wfeFlowRunPrcs.updateParent(runId, fl.getPrcsId(), null, null,
                                        fl.getFlowPrcs(), null, fl.getParent(), fl.getParentPrcsId());

                            } else {
                                if (0 == j) {
                                    flowRunPrcs = list.get(0);
                                    flowRunPrcs.setParent(flowRunPrcs.getParent() + "," + fl.getParent());
                                    flowRunPrcs.setParentPrcsId(flowRunPrcs.getParentPrcsId() + "," + fl.getParentPrcsId());
                                    wfeFlowRunPrcs.updateParent(runId, flowRunPrcs.getPrcsId(), null, null,
                                            flowRunPrcs.getFlowPrcs(), null, flowRunPrcs.getParent(), flowRunPrcs.getParentPrcsId());
                                }
                            }
                        /*//更新父亲节点
                        if (0 == j) {

                            flowRunPrcs = list.get(0);
                            flowRunPrcs.setParent(flowRunPrcs.getParent() + "," + fl.getParent());
                            flowRunPrcs.setParentPrcsId(flowRunPrcs.getParentPrcsId() + "," + fl.getParentPrcsId());
                            wfeFlowRunPrcs.updateParent(runId, flowRunPrcs.getPrcsId(), null, null,
                                    flowRunPrcs.getFlowPrcs(), null, flowRunPrcs.getParent(), flowRunPrcs.getParentPrcsId());
                        }*/

                            if (null == check && 0 == j) {
                                list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), null, branchCount);
                                StringBuffer stringBuffer = new StringBuffer();
                                String masterUser = "";
                                for (FlowRunPrcs fr : list) {
                                    if ("0".equals(topDefaultArray[i])) {
                                        if ("1".equals(fr.getOpFlag())) {
                                            masterUser = fr.getUserId();
                                        }
                                    }
                                    stringBuffer.append(fr.getUserId()).append(",");
                                }
                                workService.todoWorkSmsBoby(masterUser, fpArray[i], tableName, runId.toString(), runName, flowId.toString(),
                                        String.valueOf(fl.getPrcsId() - 1), currentPrcsId.toString(), tabId, topDefaultArray[i], smsContent, request, smsType, users, orgadd, stringBuffer.toString(), "");

                            }


                        } else {
                            if (check != null) {
                                fl.setPrcsFlag("6");
                            } else {
                                workService.todoWorkSmsBoby(beginByUser, fpArray[i], tableName, runId.toString(), runName, flowId.toString(),
                                        prcsId.toString(), currentPrcsId.toString(), tabId, topDefaultArray[i], smsContent, request, smsType, users, orgadd, jingbanArray[j], "");
                            }
                            wfeFlowRunPrcs.save(fl);
                        }

                    } else {
                        List<FlowRunPrcs> flowRunPrcs = wfeFlowRunPrcs.selectFind(fl.getPrcsId(), fl.getRunId(), fl.getFlowPrcs(), fl.getUserId(), null);
                        if (flowRunPrcs.size() > 0) {
                            for (FlowRunPrcs frp : flowRunPrcs
                            ) {
                                flowRunPrcsMapper.updateState(fl);
                            }
                        } else {
                            wfeFlowRunPrcs.save(fl);
                        }
                        workService.todoWorkSmsBoby(beginByUser, fpArray[i], tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefaultArray[i], smsContent, request, smsType, users, orgadd, jingbanArray[j], "");

                    }
                    //执行发送微信推送消息的方法
                    //weixinPublicService.saveWorkWeChatNotice(jingbanArray[j], weChatTriggerPlugIn, flowStep, fl);*//**//*

                    /** lr               添加转发日志信息         **/
                    FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
                    flowRunLog.setType(Constant.TYPE1);
                    flowRunLog.setRunId(fl.getRunId());
                    flowRunLog.setFlowId(fl.getFlowId());
                    flowRunLog.setPrcsId(prcsId);
                    flowRunLog.setFlowPrcs(currentPrcsId);
                    flowRunLog.setGoProcsId(fl.getFlowPrcs() + "");
                    flowRunLog.setTransactor(usersService.getUserNameById(alljingbanArray[i]));
                    wfeLog.addFlowRunLog(flowRunLog);

                    /*                添加完毕                **/


                }
            }

            workFlowPlugin.plugin(1);
            toJson.setMsg("OK");
            toJson.setFlag(0);
        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
            toJson.setFlag(1);
        }
        return toJson;
    }


    public void viewRead(FlowRun flowRun, String viewUser, Integer prcsId, Integer currentPrcsId, String tabId, String flowPrcs) {
        if (!StringUtils.checkNull(viewUser)) {
            //修改传阅人
            flowRun.setViewUser(viewUser);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("runId", flowRun.getRunId());
            map.put("viewUser", viewUser);
            wfeFlowRun.updateState(map);

            //添加判断大足的  只有最后一步才会传阅
            SysPara myproject = sysParaMapper.querySysPara("MYPROJECT");
            if (myproject != null && !StringUtils.checkNull(myproject.getParaValue()) && myproject.getParaValue().equals("dazu") && !StringUtils.checkNull(flowPrcs) && !flowPrcs.equals("0")) {
                FlowProcess process = flowProcessMapper.findProcess(flowRun.getFlowId(), Integer.parseInt(flowPrcs));
                if (!StringUtils.checkNull(process.getPrcsTo()) && !process.getPrcsTo().equals("0,")) {
                    return;
                }
            }

            //添加到传阅表
            String[] viewUserStr = viewUser.split(",");
            Date date = new Date();
            for (String s : viewUserStr) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sdf.format(date);
                Map map2 = new HashMap();
                map2.put("runId", flowRun.getRunId());
                map2.put("userId", s);
                map2.put("readDate", "0000-00-00 00:00:00");
                map2.put("createDate", dateStr);
                map2.put("readFlag", 0);
                map2.put("prcsId", prcsId);
                map2.put("flowPrcs", currentPrcsId);
                if (!StringUtils.checkNull(tabId)) {
                    map2.put("tableId", tabId);
                }
                toBeReadMapper.insertFlowRunRead(map2);
            }
        }
    }

    /**
     * 根据prcsId和runId修改flow_run_prcs表
     *
     * @param runId
     * @param prcsId
     * @param prcsFlag
     * @param userId
     * @param flowPrcs
     * @param prcsTime
     * @param deliverTime
     * @param opFlag
     * @param branchCount
     * @return
     */
    public int updateFrpByPrcsId(Integer runId, Integer prcsId, String prcsFlag, String userId,
                                 Integer flowPrcs, String prcsTime, String deliverTime, Integer opFlag, String branchCount) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("runId", runId);
        map.put("prcsId", prcsId);
        map.put("prcsFlag", prcsFlag);
        map.put("userId", userId);
        map.put("flowPrcs", flowPrcs);
        map.put("prcsTime", prcsTime);
        map.put("deliverTime", deliverTime);
        map.put("opFlag", opFlag);
        map.put("branchCount", branchCount);
        int count = wfeFlowRunPrcs.updateSql(map);
        return count;
    }

    /**
     * 操作当前步骤状态，强制转交、传阅，触发器
     *
     * @param runId
     * @param prcsId
     * @param flowPrcs
     * @param currentPrcsId
     * @param userId
     * @param topDefault
     * @param flowRun
     * @param viewUser
     * @param tabId
     * @param beginUser
     * @param beginTime
     * @param runName
     */
    public TriggerPlugIn updateFlowRunPrcs(Integer runId, Integer prcsId, String flowPrcs,
                                           Integer currentPrcsId, String userId,
                                           String topDefault, FlowRun flowRun, String viewUser,
                                           String tabId, String beginUser, String beginTime, String runName) {
        //转交操作，判断有没有勾选（暂不办结本步骤，可继续办理）。若勾选则不将本步骤的经办待办数据办结
        String turnType = request.getParameter("turnType");
        if (StringUtils.checkNull(turnType) || turnType.equals("0")) {
            //更新当前步骤流程状态值为3 已转交和办结时间
            this.updateFrpByPrcsId(runId, prcsId, "3", userId, currentPrcsId,
                    null, DateFormat.getStrDate(new Date()), null, null);
            if ("2" != (topDefault)) {
                //强制转交处理经办人流程状态
                wfeFlowRunPrcs.updateHandler(runId, prcsId, currentPrcsId, "4", null,
                        DateFormat.getStrDate(new Date()), null);
            }
        }
        if (flowRun != null) {
            viewRead(flowRun, viewUser, prcsId, currentPrcsId, tabId, flowPrcs);
        }

        /**     lr 工作流使用日志 ---转交**/
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        if (StringUtils.checkNull((String) request.getSession().getAttribute(
                "loginDateSouse"))) {
            sqlType = "xoa1001";
        }
        //触发器参数提取处公共方法
        TriggerPlugIn triggerPlugIn = this.getTrigger(runId.toString(), String.valueOf(flowRun.getFlowId()), sqlType, beginUser, beginTime, runName, flowPrcs, prcsId.toString(), currentPrcsId.toString(), tabId, request, turn);
        //触发器执行
        this.notifyNotice(triggerPlugIn);
        return triggerPlugIn;
    }


    public ToJson endFlowRunPrcs(Integer runId, Integer prcsId, String userId, Integer currentPrcsId, FlowProcess currentFp) {
        ToJson toJson = new ToJson();
        this.updateFrpByPrcsId(runId, prcsId, "4", userId, currentPrcsId, null, null, null, null);
        //获取该步流骤所有程,标志是否结束
        List<FlowRunPrcs> datas = wfeFlowRunPrcs.getFlowRunReacsAllByRunId(runId.toString());
        boolean flag = true;
        for (FlowRunPrcs flowRunPrcs : datas) {
            if (Integer.parseInt(flowRunPrcs.getPrcsFlag()) < 3) {
                flag = false;
                break;
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("endTime", DateFormat.getStrDate(new Date()));
        map.put("runId", runId);
        if (flag) {
            wfeFlowRun.updateState(map);
        }
        try {
            newFlowRun(currentFp, runId.toString(), userId);
            if (runId != null && !("").equals(runId.toString().trim())) {
                Map<String, Object> parentMap = new HashMap<>();
                parentMap.put("childRun", runId);
                FlowRunPrcs flowRunPrcs = flowRunPrcsMapper.selectParentFlowRunPrcs(parentMap);
                if (flowRunPrcs != null) {
                    //拥有父流程，办结此步骤
                    this.updateFrpByPrcsId(flowRunPrcs.getRunId(), flowRunPrcs.getPrcsId(), "3", null, flowRunPrcs.getFlowPrcs(),
                            null, DateFormat.getStrDate(new Date()), null, null);
                    Map<String, Object> maps = new HashMap<String, Object>();
                    //flowRun表更改结束时间
                    maps.put("endTime", DateFormat.getStrDate(new Date()));
                    maps.put("runId", flowRunPrcs.getRunId());
                    wfeFlowRun.updateState(maps);

                }


//                    FlowRun flowRunSon = flowRunMapper.find(Integer.parseInt(runId));
//                    if (flowRunSon.getParentRun() != 0) {
//                        overMotion(runId);
//                        //添加子到父映射
//                        sonParent(flowRunSon);
//                    }
            }
            toJson.setMsg("OK");
            toJson.setFlag(0);
        } catch (Exception e) {
            toJson.setFlag(1);
            // HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            //FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
            //flowRunLog.setType(Constant.TYPE11);
            toJson.setMsg(e.getMessage());
            L.e("work saveWork:" + e);
        }
        return toJson;
    }


    public AjaxJson getWFBack(Integer flowId, Integer runId, Integer prcsId, Integer flowPrcs, String userId) {
        AjaxJson ajaxJson = new AjaxJson();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, flowPrcs);
            List<FlowRunPrcs> list = wfeFlowRunPrcs.selectFind(prcsId, runId, flowPrcs, userId, null);
            FlowRunPrcs flowRunPrcs = list.get(0);
            Integer allowBack = Integer.parseInt(flowProcess.getAllowBack());

            mapList = reBack(flowRunPrcs, mapList, allowBack);
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            return ajaxJson;
        }
        ajaxJson.setFlag(true);
        ajaxJson.setMsg("true");
        ajaxJson.setObj(mapList);
        return ajaxJson;
    }


    //所有回退步骤
    public List<Map<String, Object>> reBack(FlowRunPrcs flowRunPrcs, List<Map<String, Object>> mapList, Integer allowBack) {

        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> mapUserInfo = new HashMap<String, Object>();
        List<Map<String, Object>> mapListUserInfo = new ArrayList<Map<String, Object>>();
        FlowRunPrcs f = null;
        if (flowRunPrcs != null && !"0".equals(flowRunPrcs.getParent())
                && !StringUtils.checkNull(flowRunPrcs.getParent()) && !"0".equals(flowRunPrcs.getParentPrcsId())
                && !StringUtils.checkNull(flowRunPrcs.getParentPrcsId())) {
            Integer runId = flowRunPrcs.getRunId();
            String parent = flowRunPrcs.getParent();
            String parentPrcsId = flowRunPrcs.getParentPrcsId();
            String[] parentArray = parent.split(",");
            String[] parentPrcsIdArray = parentPrcsId.split(",");
            int length = parentArray.length;
            for (int i = 0; i < length; i++) {
                List<FlowRunPrcs> list = wfeFlowRunPrcs.selectFind(Integer.parseInt(parentPrcsIdArray[i]), runId, Integer.parseInt(parentArray[i]), null, null);
                if (list != null && list.size() > 0) {
                    f = list.get(0);
                    map.put("id", f.getId());
                    map.put("runId", runId);
                    map.put("prcsId", f.getPrcsId());
                    map.put("flowPrcs", f.getFlowPrcs());
                    map.put("prcsName", f.getFlowProcess().getPrcsName());
                    map.put("childRun", f.getChildRun());
                } else {
                    return mapList;
                }
                if (list.size() == 1) {
                    mapUserInfo.put("userId", f.getUserId());
                    mapUserInfo.put("UserName", f.getUserName());
                    mapUserInfo.put("opFlag", f.getOpFlag());
                    mapUserInfo.put("topFlag", f.getTopFlag());
                    mapUserInfo.put("deliverTime", f.getDeliverTime());
                    map.put("userInfo", mapUserInfo);
                } else {
                    for (FlowRunPrcs flowRunPrcs1 : list) {
                        mapUserInfo.put("userId", flowRunPrcs1.getUserId());
                        mapUserInfo.put("UserName", flowRunPrcs1.getUserName());
                        mapUserInfo.put("opFlag", flowRunPrcs1.getOpFlag());
                        mapUserInfo.put("topFlag", flowRunPrcs1.getTopFlag());
                        mapUserInfo.put("deliverTime", flowRunPrcs1.getDeliverTime());
                        mapListUserInfo.add(mapUserInfo);
                    }
                    map.put("userInfo", mapListUserInfo);
                }
                mapList.add(map);
            }
            if (1 == allowBack) {
                return mapList;
            } else {
                reBack(f, mapList, allowBack);
            }
        } else {
            return mapList;
        }
        return mapList;
    }

    //工作交办附件上传
    public ToJson<Attachment> workUpload2(MultipartFile[] files, String company, String module, HttpServletRequest request) {
        ToJson<Attachment> json = new ToJson<Attachment>();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);

            List<Attachment> list = enclosureService.upload(files, company, module);

            /*   FlowRunAttach flowRunAttach = new FlowRunAttach();*/
            Object[] o = FileUploadUtil.reAttachment(list);
          /*  flowRunAttach.setRunId(Integer.valueOf(runId));
            flowRunAttach.setAttachmentId(o[0].toString());
            if (StringUtils.checkNull(flowPrcs)) {
                flowRunAttach.setFlowPrcs(0);
            } else {
                flowRunAttach.setFlowPrcs(Integer.valueOf(flowPrcs));
            }

            Date d = new Date();
            String d1 = DateFormat.getStrDate(d);
            flowRunAttach.setUploadTime(d1);
            flowRunAttach.setUploadUser(users.getUserName());
            flowRunAttach.setAttachmentName(o[1].toString());

            flowRunAttachMapper.insertSelective(flowRunAttach);

            FlowRun flowRun = wfeFlowRun.find(Integer.parseInt(runId));
            String attcahmentId = flowRun.getAttachmentId();
            String attachmentName = flowRun.getAttachmentName();
            StringBuffer id = new StringBuffer();
            StringBuffer name = new StringBuffer();
            if (attcahmentId != "" || attachmentName != "") {
                id.append(attcahmentId);
                name.append(attachmentName);
            }

            map.put("runId", runId);
            if (!StringUtils.checkNull(flowRun.getAttachmentId())) {
                if (!",".equals(flowRun.getAttachmentId().substring(flowRun.getAttachmentId().length() - 1, flowRun.getAttachmentId().length()))) {
                    flowRun.setAttachmentId(flowRun.getAttachmentId() + ",");
                }
            }
            if (!StringUtils.checkNull(flowRun.getAttachmentName())) {
                if (!"*".equals(flowRun.getAttachmentName().substring(flowRun.getAttachmentName().length() - 1, flowRun.getAttachmentName().length()))) {
                    flowRun.setAttachmentName(flowRun.getAttachmentName() + "*");
                }
            }

            map.put("attachmentId", flowRun.getAttachmentId() + o[0].toString());
            map.put("attachmentName", flowRun.getAttachmentName() + o[1].toString());
            wfeFlowRun.updateAttachment(map);*/
            json.setObj(list);
            json.setMsg("OK");
            json.setFlag(0);
            /****   lr 工作流使用添加日志 --上传附件 ****/
            /*FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
            flowRunLog.setType(Constant.TYPE8);
            flowRunLog.setPrcsId(flowRunAttach.getFlowPrcs());
            flowRunLog.setRunId(Integer.parseInt(runId));
            flowRunLog.setAccessory(flowRun.getAttachmentName() + o[1].toString());
            wfeLog.addFlowRunLog(flowRunLog);*/
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;
    }

    public ToJson<FlowRunPrcs> savework2(Integer runId, String runName, Integer prcsId,
                                         String flowPrcs, String beginTime, String beginUser, String jingbanUser, String viewUser, Users users,
                                         Integer currentPrcsId, String topDefault, String tabId, String tableName,
                                         String smsContent, String smsType, String orgadd, String parent, String topFlag) {
        ToJson<FlowRunPrcs> toJson = new ToJson<FlowRunPrcs>();
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            FlowRun flowRun = wfeFlowRun.find(runId);
            Integer flowId = flowRun.getFlowId();
            //当前步骤对应流程和实例基本信息
            FlowProcess currentFp = wfeFlowProcess.findbyprcsId(flowId, currentPrcsId);

            //当前步骤状态，强制转交、传阅，触发器业务逻辑方法
           /* this.updateFlowRunPrcs(runId, prcsId, flowPrcs, currentPrcsId, users.getUserId(), currentFp.getTopDefault(), flowRun,
                    viewUser, tabId, beginUser, beginTime, runName);
*/
            FlowRunPrcs fl = new FlowRunPrcs();

            //流程结束
            if (("0").equals(flowPrcs)) {
                workService.todoWorkSmsBoby2(flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, smsContent, request, smsType, users, orgadd, jingbanUser, viewUser);
                //结束流程
                return this.endFlowRunPrcs(runId, prcsId, users.getUserId(), currentPrcsId, currentFp);
            }
            if (!StringUtils.checkNull(viewUser)) {
                if (smsType.contains("8") && smsType.contains("9")) {
                    workService.todoWorkSmsBoby2(flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, smsContent, request, "8,9,", users, orgadd, jingbanUser, viewUser);
                } else {
                    if (smsType.contains("8")) {
                        workService.todoWorkSmsBoby2(flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, smsContent, request, "8", users, orgadd, jingbanUser, viewUser);
                    }
                    if (smsType.contains("9")) {
                        workService.todoWorkSmsBoby2(flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, smsContent, request, "9", users, orgadd, jingbanUser, viewUser);
                    }
                }
            }


            //下一步经办步骤
            String[] fpArray = flowPrcs.split(",");
            //经办人数组
            String[] alljingbanArray = jingbanUser.split("\\|");
            //主办人数组
            /* String[] beginUserArray = beginUser.split(",");*/
            //主办人相关选项数组
            String[] topDefaultArray = topDefault.split(",");

            //获取当前步骤数据
            List<FlowRunPrcs> listFrp = wfeFlowRunPrcs.selectFind(prcsId, runId, currentPrcsId, users.getUserId(), null);
            FlowRunPrcs currentFrp = listFrp.get(0);
            String branchCount = null;
            //根据是否允许并发判断并发步骤的值
            if (!"0".equals(currentFp.getSyncDeal().trim())) {
                branchCount = currentFp.getPrcsId().toString();
            } else {
                branchCount = currentFrp.getBranchCount();
            }
            if ("0".equals(currentFp.getSyncDeal().trim()) && "1".equals(currentFp.getGatherNode())) {
                branchCount = "0";
            }
            int length = fpArray.length;
            for (int i = 0; i < length; i++) {
                //步骤对应流程信息
                FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));

                if ("1".equals(flowProcess.getGatherNode())) {
                    int temp = length - 1;
                    if (i < temp) {
                        String tempFp = fpArray[i];
/*
                        String tempBeginUser = beginUserArray[i];
*/
                        String tempJingbanUser = alljingbanArray[i];
                        String tempTopDefault = topDefaultArray[i];
                        int len = temp - i;
                        for (int j = 0; j < len; j++) {
                            fpArray[i + j] = fpArray[i + j + 1];
/*
                            beginUserArray[i + j] = beginUserArray[i + j + 1];
*/
                            alljingbanArray[i + j] = alljingbanArray[i + j + 1];

                            topDefaultArray[i + j] = topDefaultArray[i + j + 1];

                        }
                        fpArray[temp] = tempFp;
/*
                        beginUserArray[temp] = tempBeginUser;
*/
                        alljingbanArray[temp] = tempJingbanUser;

                        topDefaultArray[temp] = tempTopDefault;

                        //因为做了个排序，流程数组需要重新获取
                        flowProcess = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));

                    }

                }

                String[] jingbanArray = null;
                //对应步骤经办数组
                jingbanArray = alljingbanArray[i].split(",");
                //判断该步骤是否是主办

                String beginByUser = null;
             /*   if (!"2".equals(topDefaultArray[i])) {
                    if (beginUserArray.length == 1) {
                        if (!StringUtils.checkNull(beginUserArray[0])) {
                            beginByUser = beginUserArray[0];
                        }
                    } else if (beginUserArray.length == 0) {

                    } else {
                        beginByUser = beginUserArray[i];
                    }
                }*/ /*else if ("2".equals(topDefaultArray[i])) {//无主办人办理*/
                if (jingbanArray.length > 0) {
                    //可能是无主办人有一个或多个
                    for (int j = 0; j < jingbanArray.length; j++) {
                        if (!StringUtils.checkNull(beginByUser)) {
                            beginByUser = jingbanArray[j] + ",";
                        } else {
                            beginByUser = jingbanArray[j] + ",";
                        }

                    }
                    String str = beginByUser.substring(beginByUser.length() - 1, beginByUser.length());
                    if (",".equals(str)) {
                        beginByUser = beginByUser.substring(0, beginByUser.length() - 1);
                    }
                }
                /*}*/
                for (int j = 0; j < jingbanArray.length; j++) {

                    Integer child_run = null;
                    fl = new FlowRunPrcs();
                    //添加先接收着者主办
                   /*if ("1".equals(topDefaultArray[i])) {
                        fl.setOpFlag("1");
                    } else if ("2".equals(topDefaultArray[i])) {  //无主办人会签
                        fl.setOpFlag("0");
                    } *//*else if{
                        if (StringUtils.checkNull(beginByUser)) {
                            fl.setOpFlag("1");
                        } else {
                            if (beginByUser.equals(jingbanArray[j])) {
                                fl.setOpFlag("1");
                                //添加子流程
                                try {
                                    FlowProcess flowProcesscurrent = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));
                                    child_run = newFlowRun(flowProcesscurrent, runId.toString(), jingbanArray[j]);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {*/
                    fl.setOpFlag("0");
                    /*        }
                        }
                    }*/
                /*    if (child_run != null) {
                        //当前流程添加此子流程
                        fl.setChildRun(child_run);
                    }*/
                    fl.setTopFlag(topFlag);//
                    fl.setRunId(runId);
                    fl.setPrcsId(prcsId);
                    fl.setPrcsFlag("1");
                    fl.setFlowPrcs(Integer.parseInt(fpArray[i]));
                    //查看是否有委托规则
                    try {
                        String userId = getUserId(runId.toString(), jingbanArray[j]);
                        if (userId != null && userId != "") {
                            jingbanArray[j] = userId;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    fl.setUserId(jingbanArray[j]);
                    fl.setCreateTime(DateFormat.getStrDate(new Date()));
                    fl.setPrcsTime("0000-00-00 00:00:00");
                    fl.setDeliverTime("0000-00-00 00:00:00");
                    fl.setActiveTime("0000-00-00 00:00:00");
                    fl.setParent(parent);//
                    fl.setParentPrcsId(prcsId.toString());
                    fl.setBranchCount(branchCount);
                    //强制合并
                    if ("1".equals(flowProcess.getGatherNode())) {
                        //检查该强制步骤是否存在未办理的流程
                        Integer check = wfeFlowRunPrcs.checkBranch(runId, branchCount, flowProcess.getPrcsId());
                        //查询强制合并步骤是否存在流程
                        List<FlowRunPrcs> list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), null, branchCount);
                        //获得强制合并步骤对应步骤
                        FlowRunPrcs flowRunPrcs = list.size() == 0 ? null : list.get(0);

                        if (list != null && list.size() > 0) {

                            if (check == null) {
                                //升位操作
                                if (fl.getPrcsId() > flowRunPrcs.getPrcsId()) {
                                    wfeFlowRunPrcs.updatePrcsId(runId, fl.getPrcsId(), null, "1", flowProcess.getPrcsId(), branchCount);
                                } else {
                                    wfeFlowRunPrcs.updatePrcsId(runId, null, null, "1", flowProcess.getPrcsId(), branchCount);
                                    fl.setPrcsId(flowRunPrcs.getPrcsId());
                                }

                            } else {
                                //升位操作
                                if (flowRunPrcs != null) {
                                    if (fl.getPrcsId() > flowRunPrcs.getPrcsId()) {
                                        wfeFlowRunPrcs.updatePrcsId(runId, fl.getPrcsId(), null, null, flowProcess.getPrcsId(), branchCount);
                                    } else {
                                        fl.setPrcsId(flowRunPrcs.getPrcsId());
                                    }
                                }
                                fl.setPrcsFlag("6");
                            }
                            //String parent = flowRunPrcs.getParent();
                            String parentPrcsId = flowRunPrcs.getParentPrcsId();
                            //查询当前转交用户是否存在对应流程
                            list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), fl.getUserId(), branchCount);
                            //判断是否是先接收者主办情况
                            if (list == null || list.size() == 0) {
                                //判断是否是先接收者主办情况
                                if (!"1".equals(flowProcess.getTopDefault())) {
                                    fl.setOpFlag("0");
                                }
                                if (0 == j) {
                                    fl.setParent(parent);//
                                    fl.setParentPrcsId(parentPrcsId + "," + fl.getParentPrcsId());
                                } else {
                                    fl.setParent(parent);
                                    fl.setParentPrcsId(parentPrcsId);
                                }
                                wfeFlowRunPrcs.save(fl);
                                wfeFlowRunPrcs.updateParent(runId, fl.getPrcsId(), null, null,
                                        fl.getFlowPrcs(), null, fl.getParent(), fl.getParentPrcsId());

                            } else {
                                if (0 == j) {
                                    flowRunPrcs = list.get(0);
                                    flowRunPrcs.setParent(parent);//
                                    flowRunPrcs.setParentPrcsId(flowRunPrcs.getParentPrcsId() + "," + fl.getParentPrcsId());
                                    wfeFlowRunPrcs.updateParent(runId, flowRunPrcs.getPrcsId(), null, null,
                                            flowRunPrcs.getFlowPrcs(), null, flowRunPrcs.getParent(), flowRunPrcs.getParentPrcsId());
                                }
                            }
                        /*//更新父亲节点
                        if (0 == j) {

                            flowRunPrcs = list.get(0);
                            flowRunPrcs.setParent(flowRunPrcs.getParent() + "," + fl.getParent());
                            flowRunPrcs.setParentPrcsId(flowRunPrcs.getParentPrcsId() + "," + fl.getParentPrcsId());
                            wfeFlowRunPrcs.updateParent(runId, flowRunPrcs.getPrcsId(), null, null,
                                    flowRunPrcs.getFlowPrcs(), null, flowRunPrcs.getParent(), flowRunPrcs.getParentPrcsId());
                        }*/

                            if (null == check && 0 == j) {
                                list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), null, branchCount);
                                StringBuffer stringBuffer = new StringBuffer();
                                String masterUser = "";
                                for (FlowRunPrcs fr : list) {
                                    if ("0".equals(null)) {
                                        if ("1".equals(fr.getOpFlag())) {
                                            masterUser = fr.getUserId();
                                        }
                                    }
                                    stringBuffer.append(fr.getUserId()).append(",");
                                }
                                workService.todoWorkSmsBoby2(fpArray[i], tableName, runId.toString(), runName, flowId.toString(),
                                        String.valueOf(fl.getPrcsId() - 1), currentPrcsId.toString(), tabId, smsContent, request, smsType, users, orgadd, stringBuffer.toString(), "");

                            }


                        } else {
                            if (check != null) {
                                fl.setPrcsFlag("6");
                            } else {
                                workService.todoWorkSmsBoby2(fpArray[i], tableName, runId.toString(), runName, flowId.toString(),
                                        prcsId.toString(), currentPrcsId.toString(), tabId, smsContent, request, smsType, users, orgadd, jingbanArray[j], "");
                            }
                            wfeFlowRunPrcs.save(fl);
                        }

                    } else {
                        wfeFlowRunPrcs.save(fl);
                        workService.todoWorkSmsBoby2(fpArray[i], tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, smsContent, request, smsType, users, orgadd, jingbanArray[j], "");

                    }
                    //执行发送微信推送消息的方法
                    //weixinPublicService.saveWorkWeChatNotice(jingbanArray[j], weChatTriggerPlugIn, flowStep, fl);*//**//*

                }
                /** lr               添加转发日志信息         **/
                FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
                flowRunLog.setType(Constant.TYPE18);
                flowRunLog.setRunId(fl.getRunId());
                flowRunLog.setFlowId(fl.getFlowId());
                flowRunLog.setPrcsId(prcsId);
                flowRunLog.setFlowPrcs(currentPrcsId);
                flowRunLog.setUserId(users.getUserId());
                flowRunLog.setGoProcsId(fl.getFlowPrcs() + "");
                flowRunLog.setTransactor(usersService.getUserNameById(alljingbanArray[i]));
                wfeLog.addFlowRunLog(flowRunLog);

                /*                添加完毕                **/
            }

            workFlowPlugin.plugin(1);
            toJson.setMsg("OK");
            toJson.setFlag(0);
        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * @方法描述：重写的saveWork方法。定时任务自动保存转交的方法，方法不能出现request,需要的值必须得传
     **/
    public ToJson<FlowRunPrcs> saveworks(Integer runId, String runName, Integer prcsId,
                                         String flowPrcs, String beginTime, String beginUser, String jingbanUser, String viewUser, Users users,
                                         Integer currentPrcsId, String topDefault, String tabId, String tableName,
                                         String smsContent, String smsType, String orgadd) {
        ToJson<FlowRunPrcs> toJson = new ToJson<FlowRunPrcs>();
        try {
            FlowRun flowRun = wfeFlowRun.find(runId);
            Integer flowId = flowRun.getFlowId();
            //当前步骤对应流程和实例基本信息
            FlowProcess currentFp = wfeFlowProcess.findbyprcsId(flowId, currentPrcsId);

            //当前步骤状态，强制转交、传阅，触发器业务逻辑方法
            /*this.updateFlowRunPrcs(runId, prcsId, flowPrcs, currentPrcsId, users.getUserId(), currentFp.getTopDefault(), flowRun,
                    viewUser, tabId, beginUser, beginTime, runName);*/
            //更新当前步骤流程状态值为3 已转交和办结时间
            this.updateFrpByPrcsId(runId, prcsId, "3", users.getUserId(), currentPrcsId,
                    null, DateFormat.getStrDate(new Date()), null, null);
            if ("2" != (topDefault)) {
                //强制转交处理经办人流程状态
                wfeFlowRunPrcs.updateHandler(runId, prcsId, currentPrcsId, "4", null,
                        DateFormat.getStrDate(new Date()), null);
            }
            if (flowRun != null) {
                viewRead(flowRun, viewUser, prcsId, currentPrcsId, tabId, flowPrcs);
            }
            FlowRunPrcs fl = new FlowRunPrcs();

            //流程结束
            if (("0").equals(flowPrcs)) {
                //判断是否有父流程
                Map<String, Object> parentMap = new HashMap<>();
                parentMap.put("childRun", runId);
                FlowRunPrcs parentFlowRunPrcs = flowRunPrcsMapper.selectParentFlowRunPrcs(parentMap);
                if (parentFlowRunPrcs != null) {//如果有父流程
                    FlowRun flowRun1 = wfeFlowRun.find(parentFlowRunPrcs.getRunId());
                    FlowProcess process = wfeFlowProcessMapper.findProcess(flowRun1.getFlowId(), parentFlowRunPrcs.getFlowPrcs());
                    FlowSort flowSort = flowSortMapper.getFlowSortByFlowId(flowRun1.getFlowId());
                    SmsBody smsBody = new SmsBody();
                    String title = "";
                    String context = "";
                    String remindUrl = "";
                    boolean bol = false;
                    SysPara myproject = sysParaMapper.querySysPara("MYPROJECT");
                    if (myproject != null && !StringUtils.checkNull(myproject.getParaValue())
                            && "dazu".equals(myproject.getParaValue())) {
                        bol = true;
                    }
                    //判断公文与工作流
                    if ("DOCUMENTTYPE".equals(flowSort.getSortMainType())) {
                        remindUrl = "/workflow/work/workform?opflag=" + parentFlowRunPrcs.getOpFlag() + "&flowId=" + flowRun1.getFlowId() + "&flowStep=" + (parentFlowRunPrcs.getPrcsId() + 1) + "&tableName=document&tabId=" + documentSerivce.checkRunId(flowRun1.getRunId()).getId() + "&runId=" + parentFlowRunPrcs.getRunId() + "&prcsId=" + Integer.parseInt(process.getPrcsTo()) + "&isNomalType=false";
                        System.out.print(remindUrl);
                        title = bol ? flowRun1.getRunName() : "您有新的公文需要签阅";
                        context = "流水号：" + runId + "，公文文号：" + flowRun1.getRunName();
                        smsBody = new SmsBody(users.getUserId(), "70", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
                    } else {
                        title = bol ? flowRun1.getRunName() : "您有新的工作需要办理";
                        context = "流水号：" + runId + "，工作名称/文号：" + flowRun1.getRunName();
                        remindUrl = "/work/**/flow/work/workform?opflag=" + parentFlowRunPrcs.getOpFlag() + "&flowId=" + flowRun1.getFlowId() + "&flowStep=" + (parentFlowRunPrcs.getPrcsId() + 1) + "&runId=" + parentFlowRunPrcs.getRunId() + "&prcsId=" + Integer.parseInt(process.getPrcsTo());
                        smsBody = new SmsBody(users.getUserId(), "7", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
                    }
                    String[] jingbanUsers = jingbanUser.split(",");
                    for (int i = 0; i < jingbanUsers.length; i++) {
                        smsService.saveSms(smsBody, jingbanUsers[i], "1", "1", title, context, "");
                    }
                } else {
                    workService.todoWorkSmsBobys(beginUser, flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefault, smsContent, smsType, users, orgadd, jingbanUser, viewUser);
                }
                //结束流程
                return this.endFlowRunPrcs(runId, prcsId, users.getUserId(), currentPrcsId, currentFp);
            }
            if (!StringUtils.checkNull(viewUser)) {
                if (smsType.contains("8") && smsType.contains("9")) {
                    workService.todoWorkSmsBobys(beginUser, flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefault, smsContent, "8,9,", users, orgadd, jingbanUser, viewUser);
                } else {
                    if (smsType.contains("8")) {
                        workService.todoWorkSmsBobys(beginUser, flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefault, smsContent, "8", users, orgadd, jingbanUser, viewUser);
                    }
                    if (smsType.contains("9")) {
                        workService.todoWorkSmsBobys(beginUser, flowPrcs, tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefault, smsContent, "9", users, orgadd, jingbanUser, viewUser);
                    }
                }
            }

            //下一步经办步骤
            String[] fpArray = flowPrcs.split(",");
            //经办人数组
            String[] alljingbanArray = jingbanUser.split("\\|");
            //主办人数组
            String[] beginUserArray = beginUser.split(",");
            //主办人相关选项数组
            String[] topDefaultArray = topDefault.split(",");

            //获取当前步骤数据
            List<FlowRunPrcs> listFrp = wfeFlowRunPrcs.selectFind(prcsId, runId, currentPrcsId, users.getUserId(), null);
            FlowRunPrcs currentFrp = listFrp.get(0);
            String branchCount = null;
            //根据是否允许并发判断并发步骤的值
            if (!"0".equals(currentFp.getSyncDeal().trim())) {
                branchCount = currentFp.getPrcsId().toString();
            } else {
                branchCount = currentFrp.getBranchCount();
            }
            if ("0".equals(currentFp.getSyncDeal().trim()) && "1".equals(currentFp.getGatherNode())) {
                branchCount = "0";
            }
            int length = fpArray.length;
            for (int i = 0; i < length; i++) {
                //步骤对应流程信息
                FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));

                if ("1".equals(flowProcess.getGatherNode())) {
                    int temp = length - 1;
                    if (i < temp) {
                        String tempFp = fpArray[i];
                        String tempBeginUser = beginUserArray[i];
                        String tempJingbanUser = alljingbanArray[i];
                        String tempTopDefault = topDefaultArray[i];
                        int len = temp - i;
                        for (int j = 0; j < len; j++) {
                            fpArray[i + j] = fpArray[i + j + 1];
                            beginUserArray[i + j] = beginUserArray[i + j + 1];
                            alljingbanArray[i + j] = alljingbanArray[i + j + 1];
                            topDefaultArray[i + j] = topDefaultArray[i + j + 1];
                        }
                        fpArray[temp] = tempFp;
                        beginUserArray[temp] = tempBeginUser;
                        alljingbanArray[temp] = tempJingbanUser;
                        topDefaultArray[temp] = tempTopDefault;
                        //因为做了个排序，流程数组需要重新获取
                        flowProcess = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));

                    }

                }

                String[] jingbanArray = null;
                //对应步骤经办数组
                jingbanArray = alljingbanArray[i].split(",");
                //判断该步骤是否是主办

                String beginByUser = null;
                if (!"2".equals(topDefaultArray[i])) {
                    if (beginUserArray.length == 1) {
                        if (!StringUtils.checkNull(beginUserArray[0])) {
                            beginByUser = beginUserArray[0];
                        }
                    } else if (beginUserArray.length == 0) {

                    } else {
                        beginByUser = beginUserArray[i];
                    }
                } else if ("2".equals(topDefaultArray[i])) {//无主办人办理
                    if (jingbanArray.length > 0) {
                        //可能是无主办人有一个或多个
                        for (int j = 0; j < jingbanArray.length; j++) {
                            if (!StringUtils.checkNull(beginByUser)) {
                                beginByUser += jingbanArray[j] + ",";
                            } else {
                                beginByUser = jingbanArray[j] + ",";
                            }

                        }
                        String str = beginByUser.substring(beginByUser.length() - 1, beginByUser.length());
                        if (",".equals(str)) {
                            beginByUser = beginByUser.substring(0, beginByUser.length() - 1);
                        }
                    }
                }
                for (int j = 0; j < jingbanArray.length; j++) {

                    Integer child_run = null;
                    fl = new FlowRunPrcs();
                    //添加先接收着者主办
                    if ("1".equals(topDefaultArray[i])) {
                        fl.setOpFlag("1");
                    } else if ("2".equals(topDefaultArray[i])) {  //无主办人会签
                        fl.setOpFlag("0");
                    } else {
                        if (StringUtils.checkNull(beginByUser)) {
                            fl.setOpFlag("1");
                        } else {
                            if (beginByUser.equals(jingbanArray[j])) {
                                fl.setOpFlag("1");
                                //添加子流程
                                try {
                                    FlowProcess flowProcesscurrent = wfeFlowProcess.findbyprcsId(flowId, Integer.parseInt(fpArray[i]));
                                    child_run = newFlowRun(flowProcesscurrent, runId.toString(), jingbanArray[j]);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                fl.setOpFlag("0");
                            }
                        }
                    }
                    if (child_run != null) {
                        //当前流程添加此子流程
                        fl.setChildRun(child_run);
                    }
                    fl.setTopFlag(topDefaultArray[i]);
                    fl.setRunId(runId);
                    fl.setPrcsId(prcsId + 1);
                    fl.setPrcsFlag("1");
                    fl.setFlowPrcs(Integer.parseInt(fpArray[i]));
                    //查看是否有委托规则
                    try {
                        String userId = getUserId(runId.toString(), jingbanArray[j]);
                        if (userId != null && userId != "") {
                            jingbanArray[j] = userId;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    fl.setUserId(jingbanArray[j]);
                    fl.setCreateTime(DateFormat.getStrDate(new Date()));
                    fl.setPrcsTime("0000-00-00 00:00:00");
                    fl.setDeliverTime("0000-00-00 00:00:00");
                    fl.setActiveTime("0000-00-00 00:00:00");
                    fl.setParent(currentPrcsId.toString());
                    fl.setParentPrcsId(prcsId.toString());
                    fl.setBranchCount(branchCount);
                    //强制合并
                    if ("1".equals(flowProcess.getGatherNode())) {
                        //检查该强制步骤是否存在未办理的流程
                        Integer check = wfeFlowRunPrcs.checkBranch(runId, branchCount, flowProcess.getPrcsId());
                        //查询强制合并步骤是否存在流程
                        List<FlowRunPrcs> list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), null, branchCount);
                        //获得强制合并步骤对应步骤
                        FlowRunPrcs flowRunPrcs = list.size() == 0 ? null : list.get(0);

                        if (list != null && list.size() > 0) {

                            if (check == null) {
                                //升位操作
                                if (fl.getPrcsId() > flowRunPrcs.getPrcsId()) {
                                    wfeFlowRunPrcs.updatePrcsId(runId, fl.getPrcsId(), null, "1", flowProcess.getPrcsId(), branchCount);
                                } else {
                                    wfeFlowRunPrcs.updatePrcsId(runId, null, null, "1", flowProcess.getPrcsId(), branchCount);
                                    fl.setPrcsId(flowRunPrcs.getPrcsId());
                                }

                            } else {
                                //升位操作
                                if (flowRunPrcs != null) {
                                    if (fl.getPrcsId() > flowRunPrcs.getPrcsId()) {
                                        wfeFlowRunPrcs.updatePrcsId(runId, fl.getPrcsId(), null, null, flowProcess.getPrcsId(), branchCount);
                                    } else {
                                        fl.setPrcsId(flowRunPrcs.getPrcsId());
                                    }
                                }
                                fl.setPrcsFlag("6");
                            }
                            String parent = flowRunPrcs.getParent();
                            String parentPrcsId = flowRunPrcs.getParentPrcsId();
                            //查询当前转交用户是否存在对应流程
                            list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), fl.getUserId(), branchCount);
                            //判断是否是先接收者主办情况
                            if (list == null || list.size() == 0) {
                                //判断是否是先接收者主办情况
                                if (!"1".equals(flowProcess.getTopDefault())) {
                                    fl.setOpFlag("0");
                                }
                                if (0 == j) {
                                    fl.setParent(parent + "," + fl.getParent());
                                    fl.setParentPrcsId(parentPrcsId + "," + fl.getParentPrcsId());
                                } else {
                                    fl.setParent(parent);
                                    fl.setParentPrcsId(parentPrcsId);
                                }
                                wfeFlowRunPrcs.save(fl);
                                wfeFlowRunPrcs.updateParent(runId, fl.getPrcsId(), null, null,
                                        fl.getFlowPrcs(), null, fl.getParent(), fl.getParentPrcsId());

                            } else {
                                if (0 == j) {
                                    flowRunPrcs = list.get(0);
                                    flowRunPrcs.setParent(flowRunPrcs.getParent() + "," + fl.getParent());
                                    flowRunPrcs.setParentPrcsId(flowRunPrcs.getParentPrcsId() + "," + fl.getParentPrcsId());
                                    wfeFlowRunPrcs.updateParent(runId, flowRunPrcs.getPrcsId(), null, null,
                                            flowRunPrcs.getFlowPrcs(), null, flowRunPrcs.getParent(), flowRunPrcs.getParentPrcsId());
                                }
                            }
                        /*//更新父亲节点
                        if (0 == j) {

                            flowRunPrcs = list.get(0);
                            flowRunPrcs.setParent(flowRunPrcs.getParent() + "," + fl.getParent());
                            flowRunPrcs.setParentPrcsId(flowRunPrcs.getParentPrcsId() + "," + fl.getParentPrcsId());
                            wfeFlowRunPrcs.updateParent(runId, flowRunPrcs.getPrcsId(), null, null,
                                    flowRunPrcs.getFlowPrcs(), null, flowRunPrcs.getParent(), flowRunPrcs.getParentPrcsId());
                        }*/

                            if (null == check && 0 == j) {
                                list = wfeFlowRunPrcs.selectFind(null, fl.getRunId(), flowProcess.getPrcsId(), null, branchCount);
                                StringBuffer stringBuffer = new StringBuffer();
                                String masterUser = "";
                                for (FlowRunPrcs fr : list) {
                                    if ("0".equals(topDefaultArray[i])) {
                                        if ("1".equals(fr.getOpFlag())) {
                                            masterUser = fr.getUserId();
                                        }
                                    }
                                    stringBuffer.append(fr.getUserId()).append(",");
                                }
                                workService.todoWorkSmsBobys(masterUser, fpArray[i], tableName, runId.toString(), runName, flowId.toString(),
                                        String.valueOf(fl.getPrcsId() - 1), currentPrcsId.toString(), tabId, topDefaultArray[i], smsContent, smsType, users, orgadd, stringBuffer.toString(), "");

                            }


                        } else {
                            if (check != null) {
                                fl.setPrcsFlag("6");
                            } else {
                                workService.todoWorkSmsBobys(beginByUser, fpArray[i], tableName, runId.toString(), runName, flowId.toString(),
                                        prcsId.toString(), currentPrcsId.toString(), tabId, topDefaultArray[i], smsContent, smsType, users, orgadd, jingbanArray[j], "");
                            }
                            wfeFlowRunPrcs.save(fl);
                        }

                    } else {
                        wfeFlowRunPrcs.save(fl);
                        workService.todoWorkSmsBobys(beginByUser, fpArray[i], tableName, runId.toString(), runName, flowId.toString(), prcsId.toString(), currentPrcsId.toString(), tabId, topDefaultArray[i], smsContent, smsType, users, orgadd, jingbanArray[j], "");

                    }
                    //执行发送微信推送消息的方法
                    //weixinPublicService.saveWorkWeChatNotice(jingbanArray[j], weChatTriggerPlugIn, flowStep, fl);*//**//*

                    /*  *//** lr               添加转发日志信息         **//*
                    FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request)
                    flowRunLog.setType(Constant.TYPE1);
                    flowRunLog.setRunId(fl.getRunId());
                    flowRunLog.setFlowId(fl.getFlowId());
                    flowRunLog.setPrcsId(prcsId);
                    flowRunLog.setFlowPrcs(currentPrcsId);
                    flowRunLog.setGoProcsId(fl.getFlowPrcs() + "");
                    flowRunLog.setTransactor(usersService.getUserNameById(alljingbanArray[i]));
                    wfeLog.addFlowRunLog(flowRunLog);*/

                    /*                添加完毕                **/


                }
            }

            workFlowPlugin.plugin(1);
            toJson.setMsg("OK");
            toJson.setFlag(0);
        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
            toJson.setFlag(1);
        }
        return toJson;
    }

    public ToJson<FlowRunPrcs> selectFind(HttpServletRequest request, FlowRunPrcs flowRunPrcs) {
        ToJson json = new ToJson();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),
                Users.class, new Users(), redisSessionId);
        List<FlowRunPrcs> flowRunPrcss = wfeFlowRunPrcs.selectFind(flowRunPrcs.getPrcsId(), flowRunPrcs.getRunId(), flowRunPrcs.getFlowPrcs(), users.getUserId(), null);
        if (flowRunPrcss.size() > 0) {
            for (FlowRunPrcs frp : flowRunPrcss
            ) {
                if (Integer.parseInt(frp.getPrcsFlag()) < 3) {
                    json.setObject("true");
                    break;
                } else {
                    json.setObject("err");
                }
            }
        } else {
            json.setObject("true");
        }
        json.setFlag(0);
        return json;
    }

    public int updateFrpById(FlowRunPrcs frp) {
        int count = wfeFlowRunPrcs.updateFrpById(frp);
        return count;
    }


    public String getPrseSetUser(String preSetUser,String flowPrcs){
        String[] presetUsers = preSetUser.split("\\|");
        String userIds=null;
        for (int i = 0; i <presetUsers.length ; i++) {
            if (flowPrcs.equals(presetUsers[i].split(":")[0])){
                userIds = presetUsers[i].split(":")[1];
                break;
            }

        }
        return userIds;
    }
}


